简体   繁体   English

Regex-如何防止重复的特殊字符?

[英]Regex-How to prevent repeated special characters?

I don't have an experience on Regular Expressions.我没有使用正则表达式的经验。 I need to a regular expression which doesn't allow to repeat of special characters (+-*/& etc.) The string can contain digits, alphanumerics, and special characters.我需要一个不允许重复特殊字符(+-*/& 等)的正则表达式。该字符串可以包含数字、字母数字和特殊字符。

This should be valid: abc,df这应该是有效的:abc,df

This should be invalid: abc-,df这应该是无效的:abc-,df

i will be really appreciated if you can help me.如果你能帮助我,我将不胜感激。 Thanks for advance.感谢您的提前。

[\\,\\+\\-\\*\\/\\&]{2,} Add more characters in the square bracket if you want. [\\,\\+\\-\\*\\/\\&]{2,}如果需要,请在方括号中添加更多字符。
Demo https://regex101.com/r/CBrldL/2 演示https://regex101.com/r/CBrldL/2

Two solutions presented so far match a string that is not allowed. 提出了两个解决方案,到目前为止匹配是不允许的字符串。

But the tilte is How to prevent... , so I assume that the regex should match the allowed string. 但是倾斜是“ 如何预防...” ,因此我假设正则表达式应与允许的字符串匹配。 It means that the regex should: 这意味着正则表达式应:

  • match the whole string if it does not contain 2 consecutive special characters, 如果整个字符串不包含2个连续的特殊字符,则匹配整个字符串,
  • not match otherwise. 否则不匹配。

You can achieve this putting together the following parts: 您可以实现以下步骤:

  • ^ - start of string anchor, ^ -字符串锚点的开始,
  • (?!.*[...]{2}) - a negative lookahead for 2 consecutive special characters (marked here as ... ), in any place, (?!.*[...]{2}) -任意位置连续出现两个连续特殊字符(此处标记为... )的否定前瞻
  • a regex matching the whole (non-empty) string, 匹配整个(非空)字符串的正则表达式,
  • $ - end of string anchor. $ -字符串锚点的结尾。

So the whole regex should be: 因此整个正则表达式应为:

^(?!.*[!@#$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2}).+$

Note that within a char class (between [ and ] ) a backslash escaping the following char should be placed before - (if in the middle of the sequence), closing square bracket, a backslash itself and / (regex terminator). 请注意,在char类(在[]之间)中,应将转义后一个字符的反斜杠放在- (如果位于序列的中间),右方括号,反斜杠本身和/ (正则表达式终止符)之前。

Or if you want to apply the regex to individual words (not the whole string), then the regex should be: 或者,如果您要将正则表达式应用于单个单词 (而不是整个字符串),则正则表达式应为:

\b(?!\S*[!@#$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2})\S+

使用以下正则表达式匹配无效的字符串。

[^A-Za-z0-9]{2,}

[^\w,\s]{2,} This would be a shortest version to match any two consecutive special characters (ignoring space) [^\w,\s]{2,}这将是匹配任意两个连续特殊字符(忽略空格)的最短版本

If you want to consider space, please use [^\w]{2,}如果要考虑空间,请使用[^\w]{2,}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM