我正在尝试使用 Java 从以下字符串中提取 TPS 编号 - 这些字符串将从文件中读取,因此这些字符串可以以任何顺序出现(事先不知道),例如我不知道我正在处理哪个字符串 - 它可能是这两个中的任何一个:
Testing performance TPS.. ok. (795 TPS recorded for run)
Testing performance TPS.. warning: TPS seems low - it was 10 TPS and I expected to achieve over 50
例如对于第一个字符串,我想要数字 795,对于第二个字符串,我想要数字 10。
有谁知道如何使用 Java 使用正则表达式或类似的方法来做到这一点?
非常感谢
最佳答案
您需要找到输入中的第一组数字字符。数字以空格结尾。
你可以使用这个正则表达式:
String regex = "[^\\d]+(\\d+) .*";
该号码在第一组 ($1
) 中捕获。
这是一个简单的测试:
public static void main(String[] args) throws Exception {
String[] lines = {
"Testing performance TPS.. ok. (795 TPS recorded for run)",
"Testing performance TPS.. warning: TPS seems low - it was 10 TPS and I expected to achieve over 50"
};
String regex = "[^\\d]+(\\d+) .*";
Pattern p = Pattern.compile(regex);
for (String s: lines) {
Matcher m = p.matcher(s);
if (m.matches()) {
System.err.println(m.group(1));
}
}
}
输出是:
795
10
关于java - 使用正则表达式 (Java) 从这些字符串中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8476024/