To match such strings in full (omit the ^
and $
for substring matching):
$strings = (
"any",
"any4",
"any6",
" any ",
" any4 ",
" any6 ",
" any ",
" any4 ",
" any6 "
)
$strings -match '^ *any[46]? *$' # matches all of the above
To match other forms of whitespace too, use \s
in lieu of
.
To extract the tokens with whitespace trimmed:
$strings -replace '^ *(any[46]?) *$', '$1' # -> 'any', 'any4', ..., 'any4', 'any6'
(...)
forms a capture group, which $1
refers to in the replacement string. See this answer of mine for more.
As for what you tried:
[4,6]
is a character set, which means that a single input character matches any of these characters, including ,
, which is not your intent.
Your use of duplication symbol (quantifier) {0,1}
is correct (0 or 1 instance of the preceding expression), but ?
is a simpler form of the same construct (just like *
is simpler than {0,}
).
By placing $
(the end-of-input assertion) directly after {0,1}
, you didn't allow for optional trailing spaces.