简体   繁体   English

在Java中使用模式匹配

[英]Using pattern matching in Java

I have a some strings which have the pattern 我有一些具有模式的字符串

word(word-number, word-number)

I would like to use a regular expression to extract the 3 words and the 2 numbers. 我想使用正则表达式来提取3个单词和2个数字。

I am currently using this 我目前正在使用它

    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");

But no avail any help would be greatly appreciated. 但无济于事任何帮助将不胜感激。

The pattern to match word(word-number, word-number) is simply 匹配word(word-number, word-number)很简单

String regex = "(\\D+)\\((\\D+)-(\\d+), (\\D+)-(\\d+)\\)";

You are using excess spaces and capturing groups in yours. 您正在使用多余的空间并捕获您的群组。

Now, to extract each individual capture group, use the Pattern API. 现在,要提取每个捕获组,请使用Pattern 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);

You could do as @Marko says to extract capture groups. 您可以像@Marko所说的那样提取捕获组。
Then just rearrange the regex slightly. 然后稍微重新排列正则表达式。

 #  "^(.+?)\\((.+?)-(\\d+?),\\s*(.+?)-(\\d+?)\\)$"

 ^                      # BOL
 ( .+? )                # (1), word
 \(                     #  '('
 ( .+? )                # (2), word
 -                      # '-'
 ( \d+? )               # (3), number
 , \s*                  # ', '
 ( .+? )                # (4), word
 -                      # '-
 ( \d+? )               # (5), numbr
 \)                     # ')'
 $                      # EOL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM