Reputation:
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?
Upvotes: 2
Views: 132
Reputation: 425003
Just restrict the last char to "any word char except 'W'".
There are a couple of ways to do this:
Negative look-behind (easy to read):
^\w+(?<!W)-\w+$
See live demo.
Negated intersection (trainwreck to read):
^\w*[\w&&[^W]]-\w+$
See live demo.
——
The question has shifted. Here’s a new take:
^.+(?<!^W)-\w+
This allows anything as the first term except just "W".
Upvotes: 1
Reputation: 12326
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.
Upvotes: 1