From: Paul Sutton Date: 2012-06-13T13:20:23+09:00 Subject: Re: Problem with reg exp On Wed, 2012-06-13 at 10:30 +0900, cyber c. wrote: > I need to match > str1 = "ABC12A2012" > str2 = "ABC13B2013KEYWORD" > > i have to extract, > word1 = ABC, word2 = 12A2012 for str1 > word1 = ABC, word2 = 13B2013 for str2 > > i have used > str.split(/([a-zA-Z]+)(.*)(KEYWORD?)/) > > for str2 i get substrings as > "","ABC","12A2012","KEYWORD" -- Why did the nil sub string popped up? > > for str1 i get only 1 substring which is the entire string That is a pretty confusing way to use split. Normally split is used with a delimiter to split into multiple parts and you don't want the delimiter in the results: "A B C".split(/ /) => ["A", "B", "C"] Your regex actually matches the whole of string str2 and none of str1. In the case of str2 the first returned string (the empty string) is simply the part of str2 that occurred before the delimiter, just like if you did: " A B C".split(/ /) => ["", "A", "B", "C"] The only reason you are getting back any part of your original str2 string (which matches the entire delimiter) is because your delimiter includes groups (the brackets) and those are returned. This is a somewhat advanced way to use split - given the state of your regex, I suggest you start with something simpler to experiment with. (For str1, the regex doesn't match at all, so no instances of the delimiter means the entire string is returned. KEYWORD? is not an optional match for "KEYWORD", it is KEYWOR and an optional D.). I suggest your forget about using split and just match using a regex and pick up the matching groups afterwards using $1 etc, e.g. str1 =~ /^([a-zA-Z]{3})([\w]{7})(KEYWORD)?$/ word1 = $1 word2 = $2 (Even better in this case though would be to use slices such as word 1 =str1[0,3], etc). Good luck, -Paul