0

So I have this snippet of Java code:

Pattern p = Pattern.compile("* bar");
Matcher m = p.matcher("foo bar");
System.out.println(m.find());

However when I run it I get the following error:

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0 * bar ^

Not sure why this happens as when I replace Pattern p = Pattern.compile("* bar") with Pattern p = Pattern.compile("foo *") everything works as expected and the console outputs true.

2 Answers 2

2

* in regexes has a special meaning of repeat zero or more times (aka empty string, x, xx and so on will all be matched by x* for example).

When it is in the beginning, the regex engine has no idea what to repeat, hence the error. In the second example, you were saying foo, followed by zero or more spaces.

If you want to match a literal *, you have to escape it - \\*.

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

3 Comments

@bowTI, you can use bar$. $ is an anchor for end of line.
@bowTI, additionally, if you want to make the entire string matched by it, you can use .*bar$.
You can reference the javadoc too.
1

* in regex means zero or more repetition of the preceding symbol. Since you don't specify any preceding symbol, you get an error. You could use . to mean any character. Hence, for your usecase, you could write your regex as .* bar.

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.