Author Posts

May 21, 2014 at 2:21 pm

Hi everyone, I need to split text which contains random text with the dash '-' character surrounded by whitespaces and also dash without whitespaces. I need to split it around the dash which is not surrounded by whitespace. I assume this can be done with a regex, but I can't figure out the pattern.

Sample text: "this is a – sample test to demonstrate-what i wrote – above"
Desired split output: "this is a – sample test to demonstrate", "what i wrote – above"

Any help is appreciated.

May 21, 2014 at 2:33 pm

Hi John. You could use -split "\b-\b" to get the split you want.

May 21, 2014 at 3:50 pm

Thank you Stein, that worked. Can you explain what exactly does it do? I found that \b means word boundary, but that doesn't really help me understand the regex.

May 21, 2014 at 11:58 pm

"Matches at a position that is followed by a word character but not preceded by a word character, or that is preceded by a word character but not followed by a word character."

http://www.regular-expressions.info/refwordboundaries.html

May 22, 2014 at 8:22 am

Keep in mind that "word characters" means letters, numbers and underscores (mostly; there's a little bit of variance here between different regex implementations.) Relying on \b might cause you problems if the hyphen has some other non-whitespace character on either side, such as parentheses, punctuation marks, etc.

Here's a tweak to the pattern which uses negative lookbehind and lookahead assertions to make sure that the hyphen does not have a whitespace character on either side of it:

$text = 'This - is - a-(test) - One - Two - Three'

Write-Verbose -Verbose 'Split with \b pattern'
$text -split '\b-\b'

Write-Verbose -Verbose 'Split with whitespace negative assertions pattern'
$text -split '(?< !\s)-(?!\s)'

Reference on lookahead / lookbehind assertions: http://www.regular-expressions.info/lookaround.html

May 26, 2014 at 7:29 am

Thanks Dave, I guess I should spend some time on reg. expressions, I've been trying to avoid them until now 🙂

May 27, 2014 at 11:16 am

You can also use positive "Lookaround" regexes with \S

'(?<=\S)-(?=\S)' Will match any – that is immediately preceeded and immediately followed by any non-whitespace character.