0

I need advice for how to create a REGEX in the best way (with as little code as possible). Suppose I have a list (that I don't know it's length before the running time) of Strings, say:

List<String> words = Array.asList("a","b","c");

I want to create this REGEX for example: (a|b|c).* Is a loop necessary for this? Is there a way to do this in one line?

Thanks

1
  • There are better ways to do this than a regular expression. Personally I would use words.stream().anyMatch(text::startsWith). Commented Jan 10, 2020 at 4:59

1 Answer 1

3

Single line:

String regex = words.stream().map(Pattern::quote).collect(Collectors.joining("|", "(", ").*"));

The map(Pattern::quote) part is not necessary if you're absolutely sure that the "words" don't contain any regex-special characters. Keep it, if there is any microscopic chance it could happen.

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

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.