Java 从字符串中提取数字和字符串的正则表达式
Java Regex to extract numbers and strings from a string
我想从字符串中提取数字和字符串。
例如
"TU111 1998 SUMMER”
"TU-232 SU 1999"
"TU232 1999 SUMMER"
我使用两种模式 Pattern.compile("\d+")
和 Pattern.compile("[a-zA-Z]+")
得到了它
有没有办法使用一种模式来获得它?
预期的结果应该是
1=>TU 2=> 111/232 3=>1998/1999 4=>SUMMER/SU
您可以将两个正则表达式连接在一起:
[0-9]+|[a-zA-Z]+
试试这个。
Pattern pattern = Pattern.compile("((\d+)|([a-zA-Z]+))");
Matcher matcher = pattern.matcher("TU111 1998 SUMMER");
while (matcher.find()) {
System.out.println(matcher.group());
}
嘿,你必须使用 2 个正则表达式 [a-zA-Z]+|[0-9]+,也许我在下面写的不同代码可能会给你 hint.just 更新 Pattern.compile () 和字符串就足够了。
Pattern p = Pattern.compile("-?\d+(,\d+)*?\.?\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher("your string");
while (m.find()) {
numbers.add(m.group());
}
System.out.println(numbers);
我想从字符串中提取数字和字符串。
例如
"TU111 1998 SUMMER”
"TU-232 SU 1999"
"TU232 1999 SUMMER"
我使用两种模式 Pattern.compile("\d+")
和 Pattern.compile("[a-zA-Z]+")
得到了它
有没有办法使用一种模式来获得它?
预期的结果应该是
1=>TU 2=> 111/232 3=>1998/1999 4=>SUMMER/SU
您可以将两个正则表达式连接在一起:
[0-9]+|[a-zA-Z]+
试试这个。
Pattern pattern = Pattern.compile("((\d+)|([a-zA-Z]+))");
Matcher matcher = pattern.matcher("TU111 1998 SUMMER");
while (matcher.find()) {
System.out.println(matcher.group());
}
嘿,你必须使用 2 个正则表达式 [a-zA-Z]+|[0-9]+,也许我在下面写的不同代码可能会给你 hint.just 更新 Pattern.compile () 和字符串就足够了。
Pattern p = Pattern.compile("-?\d+(,\d+)*?\.?\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher("your string");
while (m.find()) {
numbers.add(m.group());
}
System.out.println(numbers);