可以使用正则表达式来匹配首个汉字前面的所有字符。具体实现如下:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = 'abc中国';
        String regex = '^(.*?)\p{Script=Han}';
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            String result = matcher.group(1);
            System.out.println(result);
        }
    }
}

上述代码中,我们使用正则表达式 ^(.*?)\p{Script=Han} 来匹配首个汉字前面的所有字符。其中 ^ 表示匹配字符串的开头,(.*?) 表示非贪婪匹配任意字符,直到遇到汉字为止,\p{Script=Han} 表示匹配所有的汉字。如果匹配成功,我们通过 matcher.group(1) 来获取匹配结果,即首个汉字前面的所有字符。

以上代码的输出结果为:

abc
Java 字符串截取:获取首个汉字前的所有字符

原文地址: https://www.cveoy.top/t/topic/qmSX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录