在Java中使用模式匹配
我有一些有图案的字符串在Java中使用模式匹配,java,regex,Java,Regex,我有一些有图案的字符串 word(word-number, word-number) 我想使用正则表达式来提取3个单词和2个数字 我目前正在使用这个 String pattern = "(.+?) (\\() (.+?)(-) (\\d+?) (,) (.+?) (-) (\\d+?) (\\))"; String a = string.replaceAll(pattern, "$1"); String b = string.replaceAll(pattern, "$
word(word-number, word-number)
我想使用正则表达式来提取3个单词和2个数字
我目前正在使用这个
String pattern = "(.+?) (\\() (.+?)(-) (\\d+?) (,) (.+?) (-) (\\d+?) (\\))";
String a = string.replaceAll(pattern, "$1");
String b = string.replaceAll(pattern, "$3");
String c = string.replaceAll(pattern, "$5");
String d = string.replaceAll(pattern, "$7");
String e = string.replaceAll(pattern, "$9");
但是没有任何帮助,我们将不胜感激。匹配
单词(单词编号,单词编号)
的模式非常简单
String regex = "(\\D+)\\((\\D+)-(\\d+), (\\D+)-(\\d+)\\)";
您正在使用多余的空间并捕获组
现在,要提取每个单独的捕获组,请使用模式
API
Matcher m = Pattern.compile(regex).matcher(string);
m.matches();
String a = m.group(1), b = m.group(2), c = m.group(3), d = m.group(4), e = m.group(5);
您可以按照@Marko的要求提取捕获组。
然后稍微重新排列正则表达式
# "^(.+?)\\((.+?)-(\\d+?),\\s*(.+?)-(\\d+?)\\)$"
^ # BOL
( .+? ) # (1), word
\( # '('
( .+? ) # (2), word
- # '-'
( \d+? ) # (3), number
, \s* # ', '
( .+? ) # (4), word
- # '-
( \d+? ) # (5), numbr
\) # ')'
$ # EOL
尝试去除正则表达式中的空白。