[英]RegEx: If first character is '%' or alphanumeric then
in nodejs, I have to following pattern在 nodejs 中,我必须遵循模式
(/^(>|<|>=|<=|!=|%)?[a-z0-9 ]+?(%)*$/i
to match only alphanumeric strings, with optional suffix and prefix with some special characters.仅匹配字母数字字符串,带有可选的后缀和前缀以及一些特殊字符。 And its working just fine.
它的工作正常。
Now I want to match the last '%' only if the first character is alphanumeric (case insensitive) or also a %.现在我只想在第一个字符是字母数字(不区分大小写)或 % 时才匹配最后一个 '%'。 Then its optionally allowed, otherwise it should not match.
然后它可选地允许,否则它不应该匹配。
Example:例子:
Should match:应该匹配:
>test
!=test
<test
>=test
<=test
%test
test
%test%
test%
Example which should not match:不应该匹配的示例:
<test% <-- its now matching, which is not correct
<test< <-- its now **not** matching, which is correct
Any Ideas?有任何想法吗?
You can add a negative lookahead after ^
like你可以在
^
之后添加一个负面的前瞻
/^(?![^a-z\d%].*%$)(?:[><]=?|!=|%)?[a-z\d ]+%*$/i
^^^^^^^^^^^^^^^^^
See the regex demo .请参阅正则表达式演示。 Details :
详情:
^
- start of string ^
- 字符串的开始(?![^az\\d%].*%$)
- fail the match if there is a char other than alphanumeric or %
at the start and %
at the end (?![^az\\d%].*%$)
- 如果开头是字母数字或%
以外的字符,结尾是%
,则匹配失败(?:[><]=?|!=|%)?
- optionally match <
, >
, <=
, >=
, !=
or %
<
、 >
、 <=
、 >=
、 !=
或%
[az\\d ]+
- one or more alphanumeric or space chars [az\\d ]+
- 一个或多个字母数字或空格字符%*
- zero or more %
chars %*
- 零个或多个%
字符$
- end of string $
- 字符串结尾You might use an alternation |
您可能会使用替代
|
to match either one of the options.匹配任一选项。
^(?:[a-z0-9%](?:[a-z0-9 ]*%)?|(?:[<>]=?|!=|%)?[a-z0-9 ]+)$
^
Start of string ^
字符串开始(?:
Non capture group (?:
非捕获组
[a-z0-9%]
Match one of the listed in the character class [a-z0-9%]
匹配字符类中列出的一个(?:[a-z0-9 ]*%)?
Optionally match repeating 0+ times any of the character class followed by %
%
|
Or(?:[<>]=?|!=|%)?
Optionally match one of the alternatives[a-z0-9 ]+
Match 1+ times any of the character class [a-z0-9 ]+
匹配任意字符类的 1+ 次)
Close non capture group )
关闭非捕获组$
End of string $
字符串结尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.