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.

IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756
  • 1
    I don't know why everybody is using \\ here. – Dave Newton Mar 04 '13 at 17:43
  • Thanks for the suggestion @DaveNewton - what would you use instead of \\? – IAmYourFaja Mar 04 '13 at 17:44
  • One slash do escape the next character (for the regex) and another slash to escape the slash (for Java). – Zutty Mar 04 '13 at 17:44
  • Ahhh gotchya - hyphen is apparently an escape character, which is why I put it in there. – IAmYourFaja Mar 04 '13 at 17:46
  • @DirtyMikeAndTheBoys Hyphens have meaning in ranges; outside of a range I don't see why it needs to be escaped. – Dave Newton Mar 04 '13 at 17:47
  • 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., http://stackoverflow.com/questions/9589074/regex-should-hyphens-be-escaped. – Dave Newton Mar 04 '13 at 17:57

2 Answers2

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.

Zutty
  • 5,357
  • 26
  • 31
  • 2
    You could use `\d` instead of `[0-9]`. – Crozin Mar 04 '13 at 17:42
  • Thanks @Zutty (+1) - so would `MaxL\\-\d+` match against 1+ occurrences of any number? When I use that I get a compiler error... – IAmYourFaja Mar 04 '13 at 17:42
  • 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? – IAmYourFaja Mar 04 '13 at 17:45
  • 1
    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., http://stackoverflow.com/questions/9589074/regex-should-hyphens-be-escaped. – Dave Newton Mar 04 '13 at 17:57
  • Good point. Made another edit. It was just laziness on my part, but I shouldn't promote poor coding practice. – Zutty Mar 04 '13 at 18:00
1

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

if(!data.matches("MaxL\\-.*"))
    throw new IllegalArgumentException("Did not match.");
Chris
  • 923
  • 1
  • 8
  • 11