1

I have to extract values from string using regex groups.

Inputs are like this,

-> 1
-> 5.2
-> 1(2)
-> 3(*)
-> 2(3).2
-> 1(*).5

Now I write following code for getting values from these inputs.

String stringToSearch = "2(3).2";
Pattern p = Pattern.compile("(\\d+)(\\.|\\()(\\d+|\\*)\\)(\\.)(\\d+)");
Matcher m = p.matcher(stringToSearch);

System.out.println("1: "+m.group(1)); // O/P: 2
System.out.println("3: "+m.group(3)); // O/P: 3
System.out.println("3: "+m.group(5)); // O/P: 2

But, my problem is only first group is compulsory and others are optional.

Thats why I need regex like, It will check all patterns and extract values.

2
  • What about using the ? qualifier to make those groups optional? (Might be totally missing what you are asking) Commented Jan 23, 2015 at 11:40
  • @Andy I tried also that but, It gives null values for groups.... Commented Jan 23, 2015 at 11:41

2 Answers 2

2

Use non-capturing groups and turn them to optional by adding ? quantifier next to those groups.

^(\d+)(?:\((\d+|\*)\))?(?:\.(\d+))?$

DEMO

Java regex would be,

"(?m)^(\\d+)(?:\\((\d\+|\\*)\\))?(?:\\.(\\d+))?$"

Example:

String input = "1\n" + 
        "5.2\n" + 
        "1(2)\n" + 
        "3(*)\n" + 
        "2(3).2\n" + 
        "1(*).5";
Matcher m = Pattern.compile("(?m)^(\\d+)(?:\\((\\d+|\\*)\\))?(?:\\.(\\d+))?$").matcher(input);
while(m.find())
{
    if (m.group(1) != null)
    System.out.println(m.group(1));
    if (m.group(2) != null)
    System.out.println(m.group(2));
    if (m.group(3) != null)
    System.out.println(m.group(3));
}
Sign up to request clarification or add additional context in comments.

2 Comments

It gives "Invalid escape sequence" in java
it works for me. Check the update.. You need to escape the backslash one more time.
1

Here is an alternate approach that is simpler to understand.

  1. First replace all non-digit, non-* characters by a colon
  2. Split by :

Code:

String repl = input.replaceAll("[^\\d*]+", ":");
String[] tok = repl.split(":");

RegEx Demo

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.