Reputation: 1030
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.
Upvotes: 1
Views: 140
Reputation: 174874
Use non-capturing groups and turn them to optional by adding ?
quantifier next to those groups.
^(\d+)(?:\((\d+|\*)\))?(?:\.(\d+))?$
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));
}
Upvotes: 2
Reputation: 786319
Here is an alternate approach that is simpler to understand.
*
characters by a colon:
Code:
String repl = input.replaceAll("[^\\d*]+", ":");
String[] tok = repl.split(":");
Upvotes: 1