[英]Java Regex to extract numbers and strings from a string
I want to extract numbers and strings from a string.我想从字符串中提取数字和字符串。
Ex.前任。
"TU111 1998 SUMMER”
“TU111 1998 夏季”
"TU-232 SU 1999"
“TU-232 SU 1999”
"TU232 1999 SUMMER"
“TU232 1999 夏季”
I was able to get it using two patterns Pattern.compile("\\\\d+")
and Pattern.compile("[a-zA-Z]+")
Is there a way to get it using one pattern?我能够使用两种模式来获得它
Pattern.compile("\\\\d+")
和Pattern.compile("[a-zA-Z]+")
有没有办法使用一种模式来获得它?
The expected outcome should be预期的结果应该是
1=>TU 2=> 111/232 3=>1998/1999 4=>SUMMER/SU
1=>TU 2=> 111/232 3=>1998/1999 4=>夏季/苏
Try with this.试试这个。
Pattern pattern = Pattern.compile("((\\d+)|([a-zA-Z]+))");
Matcher matcher = pattern.matcher("TU111 1998 SUMMER");
while (matcher.find()) {
System.out.println(matcher.group());
}
Hey you have to use 2 regexes [a-zA-Z]+|[0-9]+ and maybe the different code I wrote below might give you a hint.just updating Pattern.compile() and string will be enough.嘿,你必须使用 2 个正则表达式 [a-zA-Z]+|[0-9]+ ,也许我下面写的不同代码可能会给你一个提示。只需更新 Pattern.compile() 和 string 就足够了。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.