Exclude a letter in Regex Pattern

Ludwig von Drake :

I am trying to create a Regex pattern for <String>-<String>. This is my current pattern:

(\w+\-\w+).

The first String is not allowed to be "W". However, it can still contain "W"s if it's more than one letter long.

For example: W-80 -> invalid W42-80 -> valid

How can this be achieved?

vbezhenar :

So your first string can be either: one character but not W or 2+ characters. Simple pattern to achieve that is:

([^W]|\w{2,})-\w+

But this pattern is not entirely correct, because now it allows any character for first part, but originally only \w characters were expected to be allowed. So correct pattern is:

([\w&&[^W]]|\w{2,})-\w+

Pattern [\w&&[^W]] means any character from \w character class except W character.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11685&siteId=1