# Strange result using String#split

**URL:** <https://www.ruby-forum.com/t/strange-result-using-string-split/145098>\
**Category:** Ruby\
**Created:** [August 6, 2008, 12:21am UTC](https://www.ruby-forum.com/t/strange-result-using-string-split/145098 "2008-08-06T00:21:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ryan\_Wallace](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/46a35a/32.png) [@Ryan\_Wallace](https://www.ruby-forum.com/u/Ryan_Wallace)\
**Post date:** [August 6, 2008, 12:21am UTC](https://www.ruby-forum.com/t/strange-result-using-string-split/145098/1 "2008-08-06T00:21:36Z")

</div>

I am trying to split a string on all occurrences of ’ AND ’ except  
where it appears within quotes. I have a regular expression which  
works but generates strange output in a certain case:

“text\_search ‘(large red spear OR axe) AND wood’ AND material  
1”.split( /(?: AND )?(\S+ ‘.+’)(?: AND )?|(?: AND )/ )

gives:

["", “text\_search ‘(large red spear OR axe) AND wood’”, “material 1”]

I don’t understand why my regular expression is producing the blank  
entry at the beginning of the array. Can anyone lend some insight?

Thanks,  
Ryan Wallace

---

<div class="post-metadata">

**Author:** ![Ryan\_Wallace](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/46a35a/32.png) [@Ryan\_Wallace](https://www.ruby-forum.com/u/Ryan_Wallace)\
**Post date:** [August 6, 2008, 9:54am UTC](https://www.ruby-forum.com/t/strange-result-using-string-split/145098/2 "2008-08-06T09:54:44Z")

</div>

Ryan Wallace wrote:

> “text\_search ‘(large red spear OR axe) AND wood’ AND material  
> 1”.split( /(?: AND )?(\S+ ‘.+’)(?: AND )?|(?: AND )/ )
> 
> gives:
> 
> ["", “text\_search ‘(large red spear OR axe) AND wood’”, “material 1”]
> 
> I don’t understand why my regular expression is producing the blank  
> entry at the beginning of the array. Can anyone lend some insight?

“text\_search ‘(large red spear OR axe) AND wood’” is what your regex  
matches.  
“” is what comes before the match and “material 1” is what comes after  
the  
match. If a split-regex matches the beginning of a string, the first  
item in  
the returned array will be “”. Compare:

> > “a1b”.split(/1/)  
> > =\> [“a”, “b”]
> 
> > “1b”.split(/1/)  
> > =\> ["", “b”]
> 
> > “1b”.split(/(1)/)  
> > =\> ["", “1”, “b”]

I also notice that you have a greedy quantifier between the ‘’ in the  
regex.  
This will likely cause unwanted result when you have more than one pair  
of ‘’  
in your string.

HTH,  
Sebastian
