Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for validating alphabetics and numbers in the localized string

I have an input field which is localized. I need to add a validation using a regex that it must take only alphabets and numbers. I could have used [a-z0-9] if I were using only English.

As of now, I am using the method Character.isLetterOrDigit(name.charAt(i)) (yes, I am iterating through each character) to filter out the alphabets present in various languages.

Are there any better ways of doing it? Any regex or other libraries available for this?

like image 872
ManuPK Avatar asked Feb 29 '12 13:02

ManuPK


People also ask

How do I allow only letters and numbers in regex?

In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

How do you validate expressions in regex?

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything. So there's no need to write your own RegExp validator.

Which below regex is applicable for alphabets?

[A-Za-z] will match all the alphabets (both lowercase and uppercase).


1 Answers

boolean foundMatch = name.matches("[\\p{L}\\p{Nd}]*");

should work.

[\p{L}\p{Nd}] matches a character that is either a Unicode letter or digit. The regex .matches() method ensures that the entire string matches the pattern.

like image 195
Tim Pietzcker Avatar answered Oct 25 '22 23:10

Tim Pietzcker