Kazekage Gaara
Kazekage Gaara

Reputation: 15052

How to find multiple Pattern(s) (using Matcher) in Java

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?

Upvotes: 0

Views: 8912

Answers (2)

Aka
Aka

Reputation: 171

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

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

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

Upvotes: 6

Related Questions