Regular expression for alpahbet,underscore,hyphen,apostrophe only

杀马特。学长 韩版系。学妹 提交于 2021-02-16 14:19:48

问题


I want a regular expression that accept only alphabets,hyphen,apostrophe,underscore. I tried

/^[ A-Za-z-_']*$/

but its not working. Please help.


回答1:


Your regex is wrong. Try this:

/^[0-9A-Za-z_@'-]+$/

OR

/^[\w@'-]+$/

Hyphen needs to be at first or last position inside a character class to avoid escaping. Also if empty string isn't allowed then use + (1 or more) instead of * (0 or more)

Explanation:

^ assert position at start of the string
[\w@'-]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible
\w match any word character [a-zA-Z0-9_]
@'- a single character in the list @'- literally
$ assert position at end of the string



回答2:


Move the hyphen at the end or the beginig of the character class or escape it:

^[ A-Za-z_'-]*$

or

^[- A-Za-z_']*$

or

^[ A-Za-z\-_']*$

If you want all letters:

^[ \pL_'-]*$

or




回答3:


When using a hyphen in a character class, be sure to place it at the end of the character class as a best practice.

The reason for this is because the hyphen is used to signify a range of characters in the character class, and when it is at the end of the class, it will not create any ranges.




回答4:


My best bet would be :

   /[A-Za-z-\'_@0-9]+/g



回答5:


You can use the following (in Java):

String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((['_-]+)\\p{Alpha})?)*+$";

If you want to have spaces and @ also (as some have given above) try:

String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((\\s|['@_-]+)\\p{Alpha})?)*+$";


来源:https://stackoverflow.com/questions/21677535/regular-expression-for-alpahbet-underscore-hyphen-apostrophe-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!