4

I'm trying to find whether the string has only numbers and special characters.

I tried below code but it isn't working

String text="123$%$443";
String regex = "[0-9]+";
String splChrs = "-/@#$%^&_+=()" ;
if ((text.matches(regex)) && (text.matches("[" + splChrs + "]+"))) {
  System.out.println("no alphabets");
}
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Harini
  • 195
  • 3
  • 14
  • what do you mean "no alphabets"? if you mean "doesn't contain letters", all you need to check is whether it contains a letter somewhere – Stultuske Jun 03 '19 at 06:52
  • Your two regular expressions and the logical `&&` do *not* check `text` for containining *no* letters `[a-z]`. –  Jun 03 '19 at 06:54
  • 1
    Only no English letters or any letters? – Ori Marko Jun 03 '19 at 06:59

4 Answers4

14

Just exclude using ^ the alphabetical letters:

[^a-zA-Z]+

See demo

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
6

If you want to check that text does not contain any letter [A-Za-z], try this:

if (!text.matches("[A-Za-z]+")) {
  System.out.println("no letters");
}

If you want to check that text contains only numbers and the given special characters, try this:

String regex = "[0-9\\-/@#$%^&_+=()]+";
if (text.matches(regex)) {
  System.out.println("no letters");
}

Note that the - must be escpade by a \ which itself must be escaped.

  • double quotes " it is also a special character how can i add it? – Harini Jun 03 '19 at 09:16
  • How can i add backslash \ – Harini Jun 03 '19 at 09:23
  • String regex="[0-9\\-/@~#$%!^&'*<>,-./:\"`;?{}|_+=()\\s]+"; i am using like this now i had to add backslash \ and square brackets [ ].How can i add it?and also tell me if i missed any special character. – Harini Jun 03 '19 at 09:33
2

Here are several solutions that might work for various requirements:

Text must have no ASCII-only letters

if (text.matches("\\P{Alpha}+")) {
  System.out.println("No ASCII letters");
}

Text must have no letter from the whole BMP plane

if (text.matches("\\P{L}+")) {
  System.out.println("No Unicode letters");
}

Text must have no alphabetic chars

if (text.matches("\\P{IsAlphabetic}+")) {
  System.out.println("No alphabetic chars");
}

*Note: the IsAlphabetic class includes L, Nl (Letter number) and Other_Alphabetic categories and might be too broad, but is good if you need to check for letters and diacritics.

The String#matches method requires a full string match, hence no anchors (^/\A and $/\z) are used in the above code snippets.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

in java regex 'match' and 'find' are different methods.If your string just contains letters you wanna find,use 'find'.Or if your wanna match the whole string,use 'match'

user9940960
  • 134
  • 4