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.
Hi John. You could use -split “\b-\b” to get the split you want.
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.
“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.”
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: Regex Tutorial - Lookahead and Lookbehind Zero-Length Assertions
Thanks Dave, I guess I should spend some time on reg. expressions, I’ve been trying to avoid them until now
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.