2

I am having some trouble getting regex to match a string in Java. Here are the strings I want to match: String Transformation Action and Transformation Action. Basically, if String is present, I want to match it, otherwise I would only match the remaining String.

I tried to utilize non-capturing group in regex, however it is not working.

Here is my regex: String regexFilter = "(?:String) (Transformation) (Action)";. This will match String Transformation Action, however as soon as I take away String, it will not match.

1

3 Answers 3

2

You need to make the String part optional by using a ?:

String regexFilter = "(?:String )?(Transformation) (Action)";

Also, there isn't much point in putting capturing groups around literal text (e.g. Transformation and Action) since you always know what those groups will capture.

String regexFilter = "(?:String )?Transformation Action";
Sign up to request clarification or add additional context in comments.

3 Comments

What if I also want "Action" to be optional too? I tried the same with "Action" and it did not work as well as "String".
@Froggy Did you try (?:String )?Transformation(?: Action)??
Ah, I see. I did that except I did put a space between "Transformation" and "Action" group.
1

Make String part optional using this regex:

String regexFilter = "\\b(?:String )?Transformation Action\\b";

PS: I have also added \\b (word boundary) to make your don't match Transformation Action111 OR xyzTransformation Action type strings.

Comments

1

You need to make the non-capturing group optional. The ? quantifier means match (1 or 0 times)

String regexFilter = "(?:String )?(Transformation) (Action)";

Comments

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.