-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
  • 34,719
  • 24
  • 185
  • 251
AIEnthusiast
  • 167
  • 1
  • 1
  • 10

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
  • 35,525
  • 9
  • 94
  • 135
Yossi Vainshtein
  • 3,525
  • 2
  • 21
  • 37
  • 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!! – AIEnthusiast May 27 '18 at 07:24