用正则表达式验证正则句语法
So I want to validate a string based on whether or not it contains only grammatical characters as well as numbers and letters.(basically A-Z, a-z, 0-9, plus periods(.), commas(,) colons(:), semicolons(;), hyphens(-), single quotes('), double quotes(") and parentheses(). I am getting a PHP error that says "Compilation failed: range out of order in character clas". What regex code should I be using?
This is the one I'm currently using:
^[a-zA-Z0-9_:;-()'\" ]*^
所以我想根据字符串是否只包含语法字符以及数字和字母来验证字符串。 (基本上是AZ,az,0-9,加上句号(。),逗号(,)冒号(:),分号(;),连字符( - ),单引号('),双引号(“)和括号() 我收到一个PHP错误,上面写着“编译失败:字符串中的乱序范围”。我应该使用什么正则表达式代码? p>
这是我目前使用的那个 :
^ [a-zA-Z0-9 _:; - ()'\“] * ^ code> p>
div>
You need to escape -
which would then become this ^[a-zA-Z0-9_:;\-()'\" ]*
. -
has a special meaning inside character set so it needs to be escaped. ^
in the end is also not necessary. The regex can also simplified using \w
like this
^[\w:;()'"\s-]*
\w
matches letters, digits, and underscores.
The problem is that you have a dash character in the regex, which the parser is interpreting as a range instead of as a literal dash. You can fix that by:
- Escaping it with a backslash (
^[a-zA-Z0-9_:;\-()'\" ]*^
) - Putting it at the start (
^[-a-zA-Z0-9_:;()'\" ]*^
) - Putting it at the end (
^[a-zA-Z0-9_:;()'\" -]*^
)