如何在java中使用正则表达式在特定位置查找文本中的数字
如何创建在字符串文本中查找数字的方法。我包含包含以下文本的字符串列表:如何在java中使用正则表达式在特定位置查找文本中的数字,java,regex,Java,Regex,如何创建在字符串文本中查找数字的方法。我包含包含以下文本的字符串列表: Radius of Circle is 7 cm Rectangle 8 Height is 10 cm Rectangle Width is 100 cm, Some text 现在我必须找到这些行中cm前面的所有数字,这样我就不会错误地找到任何其他数字 这是如何发生的您必须使用以下正则表达式查找字符串中只有数字的组: (?:\d{1,}) \d{1,}匹配一个数字(等于[0-9]) {1,}量词-在一次和无限次之间
Radius of Circle is 7 cm
Rectangle 8 Height is 10 cm
Rectangle Width is 100 cm, Some text
现在我必须找到这些行中cm前面的所有数字,这样我就不会错误地找到任何其他数字
这是如何发生的您必须使用以下正则表达式查找字符串中只有数字的组:
(?:\d{1,})
- \d{1,}匹配一个数字(等于[0-9])
- {1,}量词-在一次和无限次之间匹配,尽可能多地匹配,根据需要返回
- (?:)捕获组
注意:在java代码中,字符
\
是转义字符。这就是为什么您必须附加另一个\
您必须使用以下正则表达式查找字符串中只有数字的组:
(?:\d{1,})
- \d{1,}匹配一个数字(等于[0-9])
- {1,}量词-在一次和无限次之间匹配,尽可能多地匹配,根据需要返回
- (?:)捕获组
注意:在java代码中,字符
\
是转义字符。这就是为什么必须附加另一个\
匹配的正则表达式是:
(\d+) cm
为了在cm
之前获得捕获的号码,您可以使用模式
和匹配器
类:
String line = "Radius of Circle is 7 cm";
Pattern pattern = Pattern.compile("(\\d+) cm");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("Value: " + matcher.group(1));
}
此示例仅与示例(1)中的行匹配,但可以轻松地为列表中包含的每一行重复此示例。有关详细信息,请参阅。匹配的正则表达式应为:
(\d+) cm
为了在cm
之前获得捕获的号码,您可以使用模式
和匹配器
类:
String line = "Radius of Circle is 7 cm";
Pattern pattern = Pattern.compile("(\\d+) cm");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("Value: " + matcher.group(1));
}
此示例仅与示例(1)中的行匹配,但可以轻松地为列表中包含的每一行重复此示例。有关更多信息,请参阅。此处使用的正确模式是:
(\\d+)\\s+cm\\b
对于单行程序,我们可以尝试使用String#replaceAll
:
String input = "Rectangle Width is 100 cm, Some text";
String output = input.replaceAll(".*?(\\d+)\\s+cm\\b.*", "$1");
System.out.println(output);
或者,要查找给定文本中的所有匹配项,我们可以尝试使用正式的模式匹配器:
String input = "Rectangle Width is 100 cm, Some text";
String pattern = "(\\d+)\\s+cm\\b";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
System.out.println("Found measurement: " + m.group(1));
}
此处使用的正确模式是:
(\\d+)\\s+cm\\b
对于单行程序,我们可以尝试使用String#replaceAll
:
String input = "Rectangle Width is 100 cm, Some text";
String output = input.replaceAll(".*?(\\d+)\\s+cm\\b.*", "$1");
System.out.println(output);
或者,要查找给定文本中的所有匹配项,我们可以尝试使用正式的模式匹配器:
String input = "Rectangle Width is 100 cm, Some text";
String pattern = "(\\d+)\\s+cm\\b";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
System.out.println("Found measurement: " + m.group(1));
}
你可以做一些事情,比如,你需要做更多的研究。你想要匹配/\d\d cm/可能是你的复制品,你需要做更多的研究。您希望匹配/\d\d cm/的可能副本