简体   繁体   中英

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.

If you are matching words inside larger string, you can replace ^ and $ with word boundary \\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. You only need to exclude those characters as well.

  • [^\\s£%&+¬¦éúíóáÉÚÍÓÁ] is a negated character class . It matches any character except whitespace or the ones you don't want.

Just replace every occurence of \\S in your pattern:

[^\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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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