Мы можем использовать lookaround, если это будет нормально, с простым выражением, таким как:
(?<=capacity).*?([0-9]+)(?=%)
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));
}
}