-3

how to differentiate hyphen in the following regex [a-zA-Z-0-9%-+-()]+ which denotes range and which denotes symbol

Parimala
  • 71
  • 1
  • 4
  • 1
    You can use hyphens in java regex classes. Just use it as the last character. Alternatively, escape it: `[\\-]`. – Keppil Jun 17 '16 at 06:17
  • I want to differentiate hyphens.For example in [a-z-0-9]+ first hyphen denotes range second hyphen denotes symbol(-) third denotes range. – Parimala Jun 17 '16 at 07:00
  • 1
    Actually, all these work: `"[-a-z0-9]+"`, `"[a-z0-9-]+"`, `"[a-z\\-0-9]+"`, and `"[a-z-0-9]+"`. That surprised me. I had expected the 4th one to throw an error, and I would suggest not using it. – Andreas Jun 17 '16 at 07:11

1 Answers1

0

See Regex - Should hyphens be escaped?

Because the hyphen is a special character, you have to escape it using the backward slash otherwise it will, as you suggested, denote a range.

Include \- to find a hyphen. If you want to match an entire string if it has a hyphen use .*\-.*, if you want...the possibilities are endless.

You can use this site for quick testing of your regex patterns: http://www.regexplanet.com/advanced/java/index.html

Community
  • 1
  • 1
Vinit Nayak
  • 103
  • 1
  • 9
  • [a-zA-Z-0-9]+ If the given regex allow - .Then how can i differentiate that hyphen. – Parimala Jun 17 '16 at 06:55
  • You don't escape using the forward slash (`/`), you escape using the backward slash (``\``). And you only need to escape inside a character class, so `.*-.*` works just file without escaping. – Andreas Jun 17 '16 at 07:06
  • the hyphen between two ranges should be considered as a symbol [a-z-0-9]+ we don't need to escape it – Parimala Jun 17 '16 at 07:23
  • Andreas is correct, I used a backward slash but wrote forward. Corrected my comment. – Vinit Nayak Jun 18 '16 at 07:47