Centixel
Centixel

Reputation: 91

Ruby split string, with exclusions

I want to take a string, and split by a substring unless that substring is prepended by a character of choice like \. It is easy to split by a string using the split() function, but what if I want to split by ' ' unless '\ '.

puts "this is a\ string".split(' ','\ ')
# => ["this", "is", "a string"]

Upvotes: 1

Views: 437

Answers (2)

coreyward
coreyward

Reputation: 80041

You can split with a regular expression with a negative lookbehind assertion.

str = "this.is\\.a.string"
str.split(/(?<!\\)\./)
# => ["this", "is\.a", "string"]

(?<!pat) - Negative lookbehind assertion: ensures that the preceding characters do not match pat, but doesn't include those characters in the matched text

Upvotes: 1

builder-7000
builder-7000

Reputation: 7627

You can use a regex with negative look-behind:

'a b c\ d e'.split(/(?<!\\) /)
=> ["a", "b", "c\\ d", "e"]

The pattern (?<!\\) matches spaces not preceded by a backslash.

Upvotes: 2

Related Questions