-2

I have a phone number which can contain below values:

• Digits: 0-9
• Special character: "#", "*", "-", "_", " ", "(", ")", "+", "?"
• Alphabets: "x", "X"

These above can be more than once in phone number. If any other value/character besides listed in above list is present it should fail.I tried creating regex but it fails with message "Dangling meta character '*'".

Below is the regex tried:

 if(!str.matches("([0-9]*|*|#|(|)|?|+|_|-)"))
   {
       System.out.println("--not matched--");
   }

Please help me in creating a regex for above.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Snehal Gupta
  • 314
  • 1
  • 2
  • 13

1 Answers1

1

You need to escape the characters *,+, ? as they have regex meaning.

You also need to escape the \ because you use java, so try

str.matches("([0-9]*|\\*|#|\\(|\\)|\\?|\\+|_|-)")

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Yossi Vainshtein
  • 3,845
  • 4
  • 23
  • 39
  • While this compiles, I'm pretty sure it will not match what OP want. Notice that `matches` expect from regex to match entire string. – Pshemo May 27 '18 at 07:14
  • @Pshemo-[0-9*#()?+_\\- ]* answer given by you matches my requirement. Thank you!! – Snehal Gupta May 27 '18 at 07:24