我的字符串的模式类似于以下内容:
我想突出显示信息。
为此,我使用以下正则表达式:
(.*SHELF)-(.*)\[.*SHELF-(.*)\]
我用regex101
进行了测试如果我尝试在 Java
上实现相同的登录Pattern pattern = Pattern.compile("(.*SHELF)-(.*)\\[.*SHELF-(.*)\\]");
Matcher matcher = pattern.matcher(inputString);
String group1 = matcher.group(1);
String group2 = matcher.group(2);
String group3 = matcher.group(3);
我遇到以下错误:
java.lang.IllegalStateException: No match found
那是为什么?
答案 0 :(得分:-1)
This post回答您的原始问题。
This expression创建捕获组并以多种形式返回所需的输出:
(([A-Z]+)-([0-9]+))\[([A-Z]+)-([A-Z0-9-]+)(\])
,如果需要,您可以进一步简化它。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(([A-Z]+)-([0-9]+))\\[([A-Z]+)-([A-Z0-9-]+)(\\])";
final String string = "PSHELF-2[PSHELF-MF-6RU]\n"
+ "SHELF-5[SHELF-M6]\n"
+ "SHELF-6[SHELF-M15]\n"
+ "SHELF-6[SHELF-M15]";
final String subst = "\\1 \\4";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
const regex = /(([A-Z]+)-([0-9]+))\[([A-Z]+)-([A-Z0-9-]+)(\])/gm;
const str = `PSHELF-2[PSHELF-MF-6RU]
SHELF-5[SHELF-M6]
SHELF-6[SHELF-M15]
SHELF-6[SHELF-M15]`;
const subst = `\nGroup 1: $1\nGroup 2: $2\nGroup3: $3\nGroup 4: $4\nGroup 5: $5`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
此图显示了表达式的工作方式,您可以在此link中可视化其他表达式:
此JavaScript代码段使用简单的100万次for
循环来显示表达式的性能。
const repeat = 1000000;
const start = Date.now();
for (var i = repeat; i >= 0; i--) {
const string = 'PSHELF-2[PSHELF-MF-6RU]';
const regex = /(([A-Z]+)-([0-9]+))\[([A-Z]+)-([A-Z0-9-]+)(\])/gm;
var match = string.replace(regex, "\nGroup #1: $1\nGroup #2: $2 \nGroup #3: $3 \nGroup #4: $4\nGroup #5: $5\n");
}
const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. ");