简体   繁体   English

排除正则表达式中的某些字符

[英]Exclude Certain characters from Regex

I have the below regex and I'm having difficultly excluding certain characters. 我有以下正则表达式,我很难排除某些字符。 I want to exclude £%&+¬¦éúíóáÉÚÍÓÁ from the string. 我想从字符串中排除£%&+¬¦éúíóáÉÚÍÓÁ

\S*(?=\S{7,30})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*

I've tried the below with no luck: 我已经尝试过以下没有运气了:

/\S*(?=\S{7,30})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=[^£%&+¬¦éúíóáÉÚÍÓÁ])\S*/

Any suggestions or pointers would be great, thanks. 任何建议或指示都会很棒,谢谢。

You must be trying to match strings that have no specified letters. 您必须尝试匹配没有指定字母的字符串。 You need to anchor your look-aheads, only that way you can achieve what you need. 你需要锚定你的前瞻,只有你能达到你需要的方式。

^(?!\S*[£%&+¬¦éúíóáÉÚÍÓÁ])(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)\S{7,30}$
 ^^^^^^^^^^^^^^^^^^^^^^^^

See demo 演示

All the lookaheads check the string at the beginning, and the length check can be moved to the end. 所有前瞻都在开头检查字符串,长度检查可以移动到结尾。 You need both ^ and $ anchors to enable length checking. 你需要^$ anchors来启用长度检查。

If you are matching words inside larger string, you can replace ^ and $ with word boundary \\b : 如果你匹配较大字符串中的单词 ,你可以用字边界\\b替换^$

\b(?!\S*[£%&+¬¦éúíóáÉÚÍÓÁ])(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)\S{7,30}\b

Or lookarounds (if these are not words, but some symbol sequences): 或者看似(如果这些不是单词,而是一些符号序列):

(?<!\S)(?!\S*[£%&+¬¦éúíóáÉÚÍÓÁ])(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)\S{7,30}(?!\S)

See another demo 另一个演示

Your regex matches those characters because \\S matches any character except whitespace. 你的正则表达式与那些字符匹配,因为\\S匹配除空格之外的任何字符。 You only need to exclude those characters as well. 您只需要排除这些字符。

  • [^\\s£%&+¬¦éúíóáÉÚÍÓÁ] is a negated character class . [^\\s£%&+¬¦éúíóáÉÚÍÓÁ]是一个否定的角色类 It matches any character except whitespace or the ones you don't want. 它匹配任何字符,除了空格或您不想要的字符。

Just replace every occurence of \\S in your pattern: 只需替换模式中每个出现的\\S

[^\s£%&+¬¦éúíóáÉÚÍÓÁ]*(?=[^\s£%&+¬¦éúíóáÉÚÍÓÁ]{7,30})(?=[^\s£%&+¬¦éúíóáÉÚÍÓÁ]*[a-z])(?=[^\s£%&+¬¦éúíóáÉÚÍÓÁ]*[A-Z])(?=[^\s£%&+¬¦éúíóáÉÚÍÓÁ]*[\d])[^\s£%&+¬¦éúíóáÉÚÍÓÁ]*

Now, I'm not sure what you're trying to achieve with that pattern. 现在,我不确定你想用这种模式实现什么。 Perhaps you can elaborate on what you're trying to match in order to improve it a bit. 也许你可以详细说明你想要匹配的内容,以便稍微改进一下。

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

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