正则表达式模式可提取Java中特定单词之前和之后的数字

时间:2019-06-09 15:48:34

标签: java regex

我只想从下面的字符串集中提取数字。基于以下条件,我想提取单词'capacity'和'%'之前的第一个数字之间的所有内容。

输入-测试硬盘容量和已用空间为&56,98%的可用空间为2%。

输出应为:98。

1 个答案:

答案 0 :(得分:0)

如果可以的话,我们可以使用环顾四周,并使用一个简单的表达式,例如:

(?<=capacity).*?([0-9]+)(?=%)

Demo

const regex = /(?<=capacity).*?([0-9]+)(?=%)/gm;
const str = `Testing Harddisk capacity and used space is &56 and it's 98% free space is 2%`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(?<=capacity).*?([0-9]+)(?=%)";
final String string = "Testing Harddisk capacity and used space is &56 and it's 98% free space is 2%";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}