Rajeev
Rajeev

Reputation: 559

How to find a string using pattern in java

please refer below code

    String line = "abc_dfgb_tf";

    String pattern1 = "(\\w+)([+-])(\\d+)(\\w+)";
    Pattern r1 = Pattern.compile(pattern1);
    Matcher m1 = r1.matcher(line);

    if (m1.find( )) 
    {
       System.out.println("Found value: " + m1.group(1) );
       System.out.println("Found value: " + m1.group(2) );
       System.out.println("Found value: " + m1.group(3) );
       System.out.println("Found value: " + m1.group(4) );
    }

in case of "abc_dfgb_tf" string m1.find( ) is coming false.

please suggest the pattern which will use for both type of string "abc_dfgb_tf" and "abc_dfgb_tf+1cbv"

help

Upvotes: 0

Views: 100

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201439

You appear to want optional everything except the first group. Something like

String line = "abc_dfgb_tf";
String pattern1 = "(\\w+)([+-]*)(\\d*)(\\w*)";
Pattern r1 = Pattern.compile(pattern1);
Matcher m1 = r1.matcher(line);

if (m1.find()) {
    System.out.println("Found value: " + m1.group(1));
    System.out.println("Found value: " + m1.group(2));
    System.out.println("Found value: " + m1.group(3));
    System.out.println("Found value: " + m1.group(4));
}

Output is

Found value: abc_dfgb_tf
Found value: 
Found value: 
Found value: 

and if I change line to String line = "abc_dfgb_tf+1cbv"; output is

Found value: abc_dfgb_tf
Found value: +
Found value: 1
Found value: cbv

Upvotes: 2

John Bollinger
John Bollinger

Reputation: 180161

You appear to want something like this:

String pattern1 = "(\\w+)(?:([+-])(\\d+)(\\w+))?";

That makes the optional tail in fact optional.

Upvotes: 5

Related Questions