[英]How to allow only one special character multiple times in a REGEX expression
I am trying to create a REGEX expression that will only allow alphanumeric characters and one special character that can be used multiple times.我正在尝试创建一个 REGEX 表达式,它只允许字母数字字符和一个可以多次使用的特殊字符。 The special characters that can be included are ()-_,.$
.可以包含的特殊字符是()-_,.$
。 For example:例如:
abc_def is valid abc_def 有效
abc-def is valid abc-def 有效
abc--def is valid abc--def 有效
abc_-def is not valid abc_-def 无效
I tried to figure it out and came up with this: [a-zA-Z0-9]*[\\-_().,\\$]?[a-zA-Z0-9]*
but that only allows the special character to appear once (so abc--def wouldn't be valid like I want it to).我试图弄清楚并想出了这个: [a-zA-Z0-9]*[\\-_().,\\$]?[a-zA-Z0-9]*
但这只允许出现一次的特殊字符(所以 abc--def 不会像我想要的那样有效)。 But if I change the ?
但如果我改变?
to a *
then multiple different special characters can be included in the string (so abc-_def would be valid but I don't want it to be).到*
然后可以在字符串中包含多个不同的特殊字符(因此 abc-_def 将是有效的,但我不希望它是)。 I tried some other stuff like: [[a-zA-Z0-9\\-]*[a-zA-Z0-9_]*...]
for example (my idea was that this would read as ( alphanumeric && '-') || (alphanumeric && '_') ||...
) but I can't find anything that will work.我尝试了其他一些东西,例如: [[a-zA-Z0-9\\-]*[a-zA-Z0-9_]*...]
(我的想法是这将读作( alphanumeric && '-') || (alphanumeric && '_') ||...
) 但我找不到任何可行的方法。
It is also worth noting that something like: abc-def-ghi-jkl-mno should be valid, so anything of the form [alphanumeric][specialcharacters][alphanumeric]
won't work.还值得注意的是: abc-def-ghi-jkl-mno 应该是有效的,因此[alphanumeric][specialcharacters][alphanumeric]
形式的任何内容都不起作用。 Additionally, the string can start and end with the special character.此外,字符串可以以特殊字符开头和结尾。
Is it possible to create a REGEX expression that will work the way I want it to?是否可以创建一个可以按照我想要的方式工作的 REGEX 表达式? Or am I stuck writing my own function?还是我坚持自己写 function? Thanks:)谢谢:)
PS I'm using this in a Validators.pattern() for form control in angular 9 in case that makes a difference PS 我在 Validators.pattern() 中使用它来控制 angular 9 中的表单,以防万一
^[a-zA-Z0-9]*([\(\)-_,\.\$])(?:\1*[a-zA-Z0-9]*)*$|^[a-zA-Z0-9]+$
will do your job ^[a-zA-Z0-9]*([\(\)-_,\.\$])(?:\1*[a-zA-Z0-9]*)*$|^[a-zA-Z0-9]+$
会做你的工作
Details:细节:
^[a-zA-Z0-9]*([\(\)-_,\.\$])
: match any character until you see first special character, place it in group 1 ^[a-zA-Z0-9]*([\(\)-_,\.\$])
:匹配任何字符,直到看到第一个特殊字符,将其放入第 1 组
(?:\1*[a-zA-Z0-9]*)*$
: match pattern starting with special character of group 1 and after that normal characters, as many as possible, until end of the string (?:\1*[a-zA-Z0-9]*)*$
:匹配模式,从组 1 的特殊字符开始,然后是正常字符,尽可能多,直到字符串结尾
^[a-zA-Z0-9]+$
: for special cases when there is no special character, eg abc
^[a-zA-Z0-9]+$
:用于没有特殊字符的特殊情况,例如abc
\1
is called back-reference
, it will be the last matched group link to learn more \1
称为back-reference
,它将是最后匹配的组链接以了解更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.