Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中使用模式匹配_Java_Regex - Fatal编程技术网

在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

尝试去除正则表达式中的空白。