Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

match only string that starts with colon (:)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading