Reputation: 2378
Given such Regex
code:
Matcher m = Pattern.compile("c:.*?(|t:){1}.*?").matcher(string);
I only want to match something like c:somesubstring|t:somesubstring
. However it also matches some thing like this:
c:somesubstring
and
c:somesubstring|a:somesubtring
How could this come? I use (|t:){1}
to guarantee that the pattern |t:
occurs and occurs only once. Will be helpful to tell me what's wrong with my regex
and give me a regex
to match only c:somesubstring|t:somesubstring
Upvotes: 2
Views: 197
Reputation: 174874
|
is a special meta character in regex which acts like a logical OR operator usually used to combine two regexes . You need to escape the |
symbol, so that it would match a literal |
symbol.
Matcher m = Pattern.compile("c:.*?(\\|t:){1}.*?").matcher(string);
much shorter.
Matcher m = Pattern.compile("c:.*?\\|t:.*?").matcher(string);
Upvotes: 1