简体   繁体   中英

Extract values from string using regex groups

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.

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

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

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