[英]How to get part of string from regex in Java
For example, I have string with range of earnings:例如,我有收入范围的字符串:
5 000-10 000 USD
and i want to extract from that string minimum and maximum value.我想从该字符串中提取最小值和最大值。 I prepared regexes, for exalmple for first value:
我准备了正则表达式,例如第一个值:
[0-9| ]*-
And now i do not know how to get that part of string.现在我不知道如何获得那部分字符串。 I tried with pattern and matcher like:
我尝试使用模式和匹配器,例如:
Pattern pattern = Pattern.compile("\\([A-Z|a-z]+");
Matcher matcher = pattern.matcher(s);
String employmentType = matcher.group(0);
But I am getting null但我得到 null
Alternative regex:替代正则表达式:
"(\\d[\\s\\d]*?)-(\\d[\\s\\d]*?)\\sUSD"
Regex in context:上下文中的正则表达式:
public static void main(String[] args) {
String input = "5 000-10 000 USD";
Matcher matcher = Pattern.compile("(\\d[\\s\\d]*?)-(\\d[\\s\\d]*?)\\sUSD").matcher(input);
if(matcher.find()) {
String minValue = matcher.group(1);
String maxValue = matcher.group(2);
System.out.printf("Min: %s, max: %s%n", minValue, maxValue);
}
}
Output: Output:
Min: 5 000, max: 10 000
Other alternative, Alt.其他选择,Alt。 2:
2:
"\\d[\\s\\d]*?(?=-|\\sUSD)"
Alt.替代品。 2 regex in context:
2 上下文中的正则表达式:
public static void main(String[] args) {
String input = "5 000-10 000 USD";
Matcher matcher = Pattern.compile("\\d[\\s\\d]*?(?=-|\\sUSD)").matcher(input);
List<String> minAndMaxValueList = new ArrayList<>(2) ;
while (matcher.find()) {
minAndMaxValueList.add(matcher.group(0));
}
System.out.printf("Min value: %s. Max value: %s%n", minAndMaxValueList.get(0), minAndMaxValueList.get(1));
}
Alt.替代品。 2 output:
2 output:
Min value: 5 000. Max value: 10 000
If you want to use space to split the string values, you can try this如果你想使用空格来分割字符串值,你可以试试这个
Pattern p = Pattern.compile("[\\s]+");
String[] result = p.split(text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.