简体   繁体   中英

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.

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

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.

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.
Then just rearrange the regex slightly.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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