1

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.

1
  • try to get rid of the whitespace in your regex. Commented Nov 23, 2013 at 19:56

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.