使用Regex和Java查找第一个匹配项 [英] Find the first occurrence with Regex and Java
问题描述
我希望能够找到第一次出现的m²,然后是前面的数字,可以是整数或十进制数。
例如
I would like to be able to find the first occurrence of m² and then numbers in front of it, could be integers or decimal numbers. E.g.
some text38m²some text,
"some text" 38 m² "some text" ,
some text48,8m²some text,
"some text" 48,8 m² "some text",
some text48m²some text等..
"some text" 48 m² "some text", etc..
到目前为止我所拥有的是:
What I have so far is:
\d\d,\d\s*(\m\u00B2)|\d\d\s*(\m\u00B2)
现在找到所有出现的内容,虽然我想可以用 findFirst()修复
。任何想法如何改进正则表达式部分?
This right now finds all occurrences, although I guess it could be fixed with findFirst()
. Any ideas how to improve the Regex part?
推荐答案
要获得第一场比赛,你只需要使用 Matcher#find()
在内如果
块:
To get the first match, you just need to use Matcher#find()
inside an if
block:
String rx = "\\d+(?:,\\d+)?\\s*m\\u00B2";
Pattern p = Pattern.compile(rx);
Matcher matcher = p.matcher("E.g. : 4668,68 m² some text, some text 48 m² etc");
if (matcher.find()){
System.out.println(matcher.group());
}
参见 IDEONE演示
请注意,您可以使用可选的非捕获组删除交替组 (?:..)?
Note that you can get rid of the alternation group using an optional non-capturing group (?:..)?
模式细分:
-
\d +
- 1+位数 -
(?:,\ d +)?
- 0+序列的逗号后跟1+位数 -
\ s *
- 0+空白符号 -
m\\\²
- m2。
\d+
- 1+ digits(?:,\d+)?
- 0+ sequences of a comma followed with 1+ digits\s*
- 0+ whitespace symbolsm\u00B2
- m2.
这篇关于使用Regex和Java查找第一个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!