问题描述
我有粗略形式的几个字符串:
I have several strings in the rough form:
[some text] [some number] [some more text]
我想使用Java Regex类提取[some number]中的文本。
I want to extract the text in [some number] using the Java Regex classes.
我大致知道我想要使用的正则表达式(尽管欢迎所有建议)。我真正感兴趣的是Java调用以获取正则表达式字符串并在源数据上使用它来生成[某个数字]的值。
I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].
编辑:我应该补充一点,我只对一个[某个数字](基本上是第一个实例)感兴趣。源字符串很短,我不打算多次查找[某些数字]。
I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].
推荐答案
完整示例:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
因为你是寻找第一个数字,你可以使用这样的正则表达式:
Since you're looking for the first number, you can use such regexp:
^\D+(\d+).*
和 m.group(1)
将返回给你第一个号码。请注意,带符号的数字可以包含减号:
and m.group(1)
will return you the first number. Note that signed numbers can contain a minus sign:
^\D+(-?\d+).*
这篇关于使用正则表达式在Java中提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!