Mark
Mark

Reputation: 227

REGEX: Match at the beginning of a string OPTIONALLY

Im building a regex to match the word combo W7. Not W73 or NW7 or 2W7.

So far I have

^w7{1}\b

which works perfectly. However, I have a problem.

I also need to have //W7 (with 2 forward slashs) also match. So if W7 or //W7 are entered they should match

Any ideas?

Thanks!

Upvotes: 0

Views: 84

Answers (3)

binfalse
binfalse

Reputation: 518

What about ^(//)?W7? the question mark indicates one or zero occurrences.

Upvotes: 1

salathe
salathe

Reputation: 51950

You could just add an optional group to your regex

^(?://)?W7\b

Remember to use a non-/ delimiter (it's tidier than escaping those slashes).

If you want the subject string to only ever contain //W7 or W7 then an alternative (full pattern) would be:

~^(?://)?W7$~D

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359786

Just add an optional // at the start.

^(//)?w7\b

You may need to escape them.

^(\/\/)?w7\b

Upvotes: 2

Related Questions