Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude Certain characters from Regex

Tags:

regex

php

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.

like image 401
llanato Avatar asked Feb 16 '26 20:02

llanato


1 Answers

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

like image 64
Wiktor Stribiżew Avatar answered Feb 19 '26 08:02

Wiktor Stribiżew