0

I have the following Java code:

String data = "MaxL-450";

if(!data.matches("MaxL\\-*"))
    throw new IllegalArgumentException("Did not match.");

When I execute it, the exception is thrown, because apparently the regex doesn't match my data string. Is there something wrong with my regex or is something else going on here? Thanks in advance.

6
  • 1
    I don't know why everybody is using \\ here. Commented Mar 4, 2013 at 17:43
  • Thanks for the suggestion @DaveNewton - what would you use instead of \\? Commented Mar 4, 2013 at 17:44
  • One slash do escape the next character (for the regex) and another slash to escape the slash (for Java). Commented Mar 4, 2013 at 17:44
  • Ahhh gotchya - hyphen is apparently an escape character, which is why I put it in there. Commented Mar 4, 2013 at 17:46
  • @DirtyMikeAndTheBoys Hyphens have meaning in ranges; outside of a range I don't see why it needs to be escaped. Commented Mar 4, 2013 at 17:47

2 Answers 2

5

* means zero or more occurrences of the previous character. You want something like "MaxL-[0-9]*", assuming you want to match a number after the dash.

Alternatively you could use "MaxL-\\d*". Note that you need two slashes in Java, since you need to escape the slash itself. Personally I like using explicit character classes (i.e. [0-9]) in Java, as its slightly easier to read as your regex inevitably gets longer and more complex.

Edit: Also, as Dave Newton points out, the escape slashes in front of the dash aren't necessary as the dash isn't inside a character class.

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

5 Comments

You could use \d instead of [0-9].
Thanks @Zutty (+1) - so would MaxL\\-\d+ match against 1+ occurrences of any number? When I use that I get a compiler error...
Thanks again @Zutty - but I tried that and getting the following error: Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )... any ideas?
My issue with "\\-" is that the "\\" isn't necessary, and IMO it leads to a bit of cargo-cult programming. Hyphens don't need to be escaped if they're not in a character range, e.g., stackoverflow.com/questions/9589074/….
Good point. Made another edit. It was just laziness on my part, but I shouldn't promote poor coding practice.
1

If you're looking for ANY chars after the hyphen:

if(!data.matches("MaxL\\-.*"))
    throw new IllegalArgumentException("Did not match.");

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.