我有几个粗略形式的字符串:
[some text] [some number] [some more text]
我想使用 Java 正则表达式类提取 [some number] 中的文本。
我大致知道我想使用什么正则表达式(尽管欢迎所有建议)。我真正感兴趣的是 Java 调用来获取正则表达式字符串并将其用于源数据以生成 [某个数字] 的值。
我应该补充一点,我只对单个[某个数字]感兴趣(基本上是第一个实例)。源字符串很短,我不会查找多次出现的[某个数字]。
最佳答案
完整示例:
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)
}
}
由于您正在查找第一个数字,因此可以使用这样的正则表达式:
^\D+(\d+).*
和m.group(1)
将返回第一个数字。请注意,带符号的数字可以包含减号:
^\D+(-?\d+).*
关于java - 在 Java 中使用正则表达式提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738019/