I am not good at regular expressions.
I dont want to allow any other characters but letters spaces and numbers. Of course the user can enter only letters or only numbers or letters and numbers but not other characters. Also he can put _ between strings example:
Hello_World123
This can be possible string. Can anyone help and build a regex for me?
You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".
Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
To ensure that a string only contains (ASCII) alphanumeric characters, underscores and spaces, use
^[\w ]+$
Explanation:
^ # Anchor the regex at the start of the string
[\w ] # Match an alphanumeric character, underscore or space
+ # one or more times
$ # Anchor the regex at the end of the string
Simply this:
^[\w ]+$
Explanation:
^ matches the start of the string
\w matches any letter, digit, or _, the same as [0-9A-Za-z_]
[\w ] is a set that that matches any character in \w, and space
+ allows one or more characters
$ matches the end of the string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With