2

I want to make a regex syntax for allowing me ASCII letters, digits, hyphens and underscores and forward slashes.

Currently I am using following syntax but it is not working

if (!id.matches("[a-zA-Z0-9_-/]+")) {
    throw new IllegalArgumentException("Invalid ID: \"" + id
            + "\". An ID may not be the empty string and must contain only ASCII letters, digits, hyphens and underscores and forward slash.");
}

However when I remove the '/' from the regex it is working fine. How can I add forward slash in this condition?

I looked into regex tutorial and it has some examples but those are individual. I want to use forward slash along with ASCII letters, digits.

3
  • 2
    Escape -. "[a-zA-Z0-9_\-/]+") or move to the end in the character class "[a-zA-Z0-9_/-]+") Commented Aug 1, 2016 at 7:32
  • read point 2 of section 2.1 from documenation Commented Aug 1, 2016 at 7:34
  • The document, it is very useful. Thanks. Commented Aug 1, 2016 at 8:50

1 Answer 1

5

You create a range with _-/.

Either put the hyphen at the end (and always keep it there):

if (!id.matches("[a-zA-Z0-9_/-]+"))
                            ^

Or, escape the hyphen to always treat it as a literal symbol:

if (!id.matches("[a-zA-Z0-9_\\-/]+"))
                            ^^^

NOTE: There has been some discussion, and it has been pointed out that in case the regular expression is going to be further improved/enhanced/expanded, the best way is to escape the hyphens that should be treated as literal - symbols inside character classes.

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

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.