ze_iliasgr
ze_iliasgr

Reputation: 193

Regular expression that matches a string only if it contains non-word characters

I need a regular expression that matches a one word string only if it contains non word characters (\W+). If there is at least one word character it shouldn't match. White spaces are guaranteed to not exist in the string.

Valid examples:
$
&
@!

Invalid examples:
yahoo!
[email protected]

The /\W/+ is not doing what i want, it validates the above examples. The language I am working is PHP in case this matters. Test it here https://regex101.com/r/766z4j/2

Upvotes: 0

Views: 862

Answers (1)

Toto
Toto

Reputation: 91518

Add anchors at the begining and at the end:

/^\W+$/

In PHP:

if (preg_match('/^\W+$/', $string)) {
    echo "Match\n";
}

You could also test the negation:

if ( ! preg_match('/\w/', $string)) {
    echo "Match\n";
}

Upvotes: 3

Related Questions