I just started learning regex and I need some help with this newbie issue. I’d like to get the string or line that starts with a colon (:).
Here’s the example of string below.
$string = "
# :test
# :testonly
:test
:testonly
"
I’d like to get the line ":test" using regex. I tried the pattern below but it doesn’t work. I’m getting a False result
$string -match '^\:test(?!\S)'
If I use
'\:test(?!\S)'
The result is True but I’m getting this
"# :test"
instead of
":test"
I hope you guys can help.
>Solution :
Your ^\:test(?!\S) pattern is looking good, you have 2 easy options, one is to split your string into an array of strings, this can be done with -split, then use this pattern with -match to filter those matching strings:
$string -split '\r?\n' -match '^:test(?!\S)'
The other easy option is to enable your regex for multi-line matching of ^ and $, this can be done by using the (?m) flag:
if($string -match '(?m)^:test(?!\S)') {
$Matches[0]
}
As aside, escaping of : with \ is unneeded.