javaregexjava-8

Capture only if string exists, if not ignore


I have a string like this:

I would like to capture only the string ee.xybfkr_eer in (:something) in the group.

but sometimes the string is without ee. part:

If this is the case, then I would like to capture the group as xybfkr_eer in (:something).

The string ee can differ, so contain other alphabetic characters.

So far, the code is:

String command = "blabla and (ee.xybfkr_eer in (:something) or 'Y'=:see)";
String patternText = "(?si).*\\W((\\w+\\.)?\\w*\\sin\\s*\\(\\s*:something\\s*\\)).*";
Matcher matcher = Pattern.compile(patternText).matcher(command);

Assert.assertTrue(matcher.matches());
System.out.println(matcher.group(1).trim());

But the

(\\w+\\.)?

part is not capturing ee. if available. This should work if ee. available, then capture it, otherwise if not exists ignore. Can somebody help me to be able to capture ee. part also if available?

I am using Java 8.


Solution

  • You may use this regex in Java:

    (?i)\(((\w+\.)?\w*\hin\h*\(\h*:something\h*\))
    

    Or in Java:

    final Pattern p = Pattern.compile(
       "(?i)\\(((\\w+\\.)?\\w*\\hin\\h*\\(\\h*:something\\h*\\))" );
    

    PS: Make sure to use Matcher#find() instead of Matcher#matches() that attempts to match complete input.

    RegEx Demo

    RegEx Details: