下面是我的文字:
12,7 C84921797-6 Provisoirement, 848,80 smth
我想用float模式提取值848,80
:[-+]?[0-9]*\\,?[0-9]+
但我使用的代码只提取匹配模式12,7
的第一个值
这是我的方法:
String display(String pattern , String result){
String value= null
Pattern p = Pattern.compile(pattern);//compiles the pattern
Matcher matcher = p.matcher(result);//check if the result contains the pattern
if(matcher.find()) {
//get the first value found corresponding to the pattern
value = matcher.group(0)
}
return value
}
当我打电话给这个方法时:
String val=display("[-+]?[0-9]*\\,?[0-9]+" ," 12,7 C84921797-6 Provisoirement, 848,80 smth" )
println("val---"+val)
输出:
val---12,7
我想在值之后使用单词smth
来提取正确的值我该怎么办?
答案 0 :(得分:2)
您可以在感兴趣的部分之后在正则表达式中添加smth
。只需在括号中放置有趣的部分即可创建组,并通过Matchers group(id)
方法引用此组匹配的部分
Pattern p = Pattern.compile("([-+]?[0-9]*\\,?[0-9]+)\\s+smth");
Matcher matcher = p.matcher(result);
if(matcher.find())
{
value = matcher.group(1); //get the first value found corresponding to the pattern
}
其他方法是使用look-ahead测试您是否感兴趣存在smth
。所以你的正则表达式看起来像
Pattern p = Pattern.compile("[-+]?[0-9]*\\,?[0-9]+(?=\\s+smth)");
由于前瞻是零长度,它不会包含在匹配中,因此您可以使用来自Matcher的group(0)
或更简单的group()
来获得您想要的结果。
答案 1 :(得分:0)
([\\d\\,]+) smth
使用此 $ 1 匹配您想要的浮点数
答案 2 :(得分:0)
如果您的号码代表后总是有smth
(注意一个空格),请尝试以下操作:
String input = "12,7 C84921797-6 Provisoirement, 848,80 smth";
// | optional sign
// | | number 1st part
// | | | optional comma, more digits part
// | | | | lookahead for " smth"
Pattern p = Pattern.compile("[-+]?\\d+(,\\d+)*(?=\\ssmth)");
Matcher m = p.matcher(input);
if (m.find()) {
System.out.println("Found --> " + m.group());
}
<强>输出强>
Found --> 848,80
答案 3 :(得分:0)