0

This seems like it should be fairly simple, but I can't seem to figure it out. I have a string that looks like this:

$string = "blah blah; something"

All I want to do is break them apart at the semicolon and space, but whenever I try to do it using $string.split("; ") it also breaks apart the first half of the string because of the space. I'm assuming that I probably need to use Regex, but don't have a good grasp of that in order to get it done.

3 Answers 3

2

System.String.Split is designed to split on every character in the string you give it:

PS > $string = "blah blah; something"   
PS > $string.Split('; b')  # This splits on ";", " ", and "b"

lah

lah

something    
PS >

If you want to split on a pattern such as "; ", you should use the -split operator:

PS > $string = "blah blah; something"
PS > $string -split '; '
blah blah
something 
PS > 
Sign up to request clarification or add additional context in comments.

Comments

1

How about simply splitting the string at ; and trimming the results from extra whitespace?

PS C:\> $string.split(';') | % { $_.trim()}
blah blah
something

A regex sure works too:

[regex]::split($string, ";\s")
blah blah
something

1 Comment

I hadn't even thought about the trim, that worked perfectly. Thanks!
0

Assuming it doesn't matter in your particular case, you could just remove the second space.

$string.Replace("; ", ";").Split(";")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.