Home > OS >  Trying to split a string into words containing only letters and/or apostrophes
Trying to split a string into words containing only letters and/or apostrophes

Time:09-11

I am trying to split the string below into words that include only letters and/or apostrophes('). However, it is returning an empty string as the first element in the array. Why is my Regex returning that empty string?

pry(main)> "  //wont won't won't".split(/[^a-z'] /i)
=> ["", "wont", "won't", "won't"]

Why is my Regex returning that empty string?

CodePudding user response:

You're trying to split (or place a break in your string if you will) at anything that does NOT match your pattern right? The very first thing in the string results in a split (or break) which in turn results in the first element being empty.

There are various ways of dealing with empty array elements like that, but I would suggest you consider using scan instead of split. Using this approach you're actually doing the more logical thing. You're looking for matches and sending those to your array (instead of looking for non-matches and splitting the original string up):

"  //wont won't won't".scan(/[a-z'] /i)  #=>  ["wont", "won't", "won't"]
  • Related