2

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

1
  • 1
    {1} does not guarantee that the preceding item does not appear more than once. Commented Dec 5, 2014 at 16:55

1 Answer 1

1

| 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);
Sign up to request clarification or add additional context in comments.

1 Comment

or put | in a char class like [|]

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.