allow parentheses and other symbols in regex

≡放荡痞女 提交于 2019-12-12 07:14:24

问题


I've made this regex:

^[a-zA-Z0-9_.-]*$

Supports:

letters [uppercase and lowercase]
numbers [from 0 to 9]
underscores [_]
dots [.]
hyphens [-]

Now, I want to add these:

spaces [ ]
comma [,]
exclamation mark  [!]
parenthesis [()]
plus [+]
equal [=]
apostrophe [']
double quotation mark ["]
at [@]
dollar [$]
percent [%]
asterisk [*]

For example, this code accept only some of the symbols above:

^[a-zA-Z0-9 _.,-!()+=“”„@"$#%*]*$

Returns:

Warning: preg_match(): Compilation failed: range out of order in character class at offset 16


回答1:


Make sure to put hyphen - either at start or at end in character class otherwise it needs to be escaped. Try this regex:

^[a-zA-Z0-9 _.,!()+=`,"@$#%*-]*$

Also note that because * it will even match an empty string. If you don't want to match empty strings then use +:

^[a-zA-Z0-9 _.,!()+=`,"@$#%*-]+$

Or better:

^[\w .,!()+=`,"@$#%*-]+$

TEST:

$text = "_.,!()+=,@$#%*-";
if(!preg_match('/\A[\w .,!()+=`,"@$#%*-]+\z/', $text)) {
   echo "error.";
}
else {
   echo "OK.";
}

Prints:

OK.



回答2:


The hyphen is being treated as a range marker -- when it sees ,-! it thinks you're asking for a range all characters in the charset that fall between , and ! (ie the same way that A-Z works. This isn't what you want.

Either make sure the hyphen is the last character in the character class, as it was before, or escape it with a backslash.

I would also point out that the quote characters you're using “”„ are part of an extended charset, and are not the same as the basic ASCII quotes "'. You may want to include both sets in your pattern. If you do need to include the non-ASCII characters in the pattern, you should also add the u modifier after the end of your pattern so it correctly picks up unicode characters.




回答3:


Try escaping your regex: [a-zA-Z0-9\-\(\)\*]

Check if this help you: How to escape regular expression special characters using javascript?




回答4:


Inside of a character class [...] the hyphen - has a special meaning unless it is the first or last character, so you need to escape it:

^[a-zA-Z0-9 _.,\-!()+=“”„@"$#%*]*$

None of the other characters need to be escaped in the character class (except ]). You will also need to escape the quote indicating the string. e.g.

'/[\']/'
"/[\"]/"



回答5:


try this

^[A-Z0-9][A-Z0-9*&!_^%$#!~@,=+,./\|}{)(~`?][;:\'""-]{0,8}$

use this link to test

trick is i reverse ordered the parenthesis and other braces that took care of some problems. And for square braces you must escape them



来源:https://stackoverflow.com/questions/18659886/allow-parentheses-and-other-symbols-in-regex

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