0

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

1
  • 1
    Just make the [+-] part optional: [+-]?. Commented Dec 22, 2014 at 20:32

2 Answers 2

5

You appear to want something like this:

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

That makes the optional tail in fact optional.

Sign up to request clarification or add additional context in comments.

1 Comment

got it .. Thnaks :) John Bollinger
2

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

1 Comment

got it .. Thnaks :) Elliott Frisch

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.