0

Suppose I have a String, say one two three one one two one. Now I'm using a Pattern and a Matcher to find any specific Pattern in the String. Like this:

Pattern findMyPattern = Pattern.compile("one");
Matcher foundAMatch = findMyPattern.matcher(myString);
while(foundAMatch.find())
           // do my stuff

But, suppose I want to find multiple patterns. For the example String I took, I want to find both one and two. Now it's a quite small String,so probable solution is using another Pattern and find my matches. But, this is just a small example. Is there an efficient way to do it, instead of just trying it out in a loop over all the set of Patterns?

2 Answers 2

6

Use the power of regular expressions: change the pattern to match one or two.

Pattern findMyPattern = Pattern.compile("one|two");
Matcher foundAMatch = findMyPattern.matcher(myString);
while(foundAMatch.find())
           // do my stuff
Sign up to request clarification or add additional context in comments.

3 Comments

I have mentioned it in the question,that it is just a small example. What if I have many,say about 100 plus,patterns to match for?
Just create the string one|two|three.. dynamically using a loop
It really depends on exactly what you're trying to do. If the patterns still look like they do in your example, you don't need a pattern at all. You can use String#contains(). Or do what Amit suggests.
0

this wont solve my issue, this way we can change (one|two) to a perticular string.

but my requirementis to change pattern one -> three & two -> four

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.