Reputation: 87
I'm checking for serial ports and I only want to use ones that match "COM1-4". I could not figure out the syntax.
Upvotes: 1
Views: 461
Reputation: 46365
Expanding a bit on Tim's answer:
If you want to match a specific range of characters, you can use []
notation - for numbers, you can say [1-4]
to match (characters) '1'
, '2'
, '3'
, or '4'
.
If you want a number at the end of a string, you mark "end of string" with the $
sign.
Finally, if you have a piece of "normal" text that you want to match exactly, you use that string. Note that if your string contains characters that have special meaning for regex
(things like .
, \
. +
, ()
, []
, etc) you need to be more careful.
When you want to match "only this in the string and nothing else", you use the anchors for "start of string" ^
and "end of string" $
to surround your expression.
This is how you end up with
^COM[1-4]$
for exactly one of COM1
, COM2
, COM3
, or COM4
.
If you could have other things before, leave off the ^
.
Upvotes: 0
Reputation: 336108
This is trivial:
^COM[1-4]$
See this tutorial about character classes and anchors.
Upvotes: 2