Java 截取字符串:获取首个汉字前的字符
可以使用正则表达式来截取字符串。以下是一个示例代码,可以实现截取首个汉字之前的所有字符,不包括空格:
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String str = 'java截取一个(km/h千米每小时)这样的字符串';
String pattern = '^[^\u4e00-\u9fa5\s]*';
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
if (m.find()) {
String result = m.group();
System.out.println(result);
}
}
}
运行结果为:
java截取一个
这样就截取到了首个汉字之前的所有字符,不包括空格。正则表达式^[^\u4e00-\u9fa5\s]*表示匹配首个汉字之前的所有字符,^表示从字符串的开头开始匹配,[^一-龥\s]表示非汉字和非空格的字符,*表示匹配0个或多个。
原文地址: https://www.cveoy.top/t/topic/qmWi 著作权归作者所有。请勿转载和采集!