From: Florian Gross Date: 2004-05-29T10:58:40+09:00 Subject: Re: regular expression help please Paul wrote: > How do I extract the name and value from the following lines: > > name=paul value=10 otherstuff=123 > > but the line may also be: > name='hello paul' value='10' otherstuff='123' irb(main):001:0> lines.scan(/^name=('?)(.*?)\1\s+value=('?)(\S*?)\3/) => [["", "paul", "", ""], ["'", "hello paul", "'", "10"]] Things start to get more interesting when Strings can also contain quoted delimiters however. (As in 'Don\'t use PHP!') Regexp::English lets us solve that case relatively easily however: > irb(main):035:0> re = Regexp::English.new do > irb(main):036:1* quoted_string = quoted_text("'") > irb(main):037:1> unquoted_string = non_whitespace > irb(main):038:1> name_val = (quoted_string | unquoted_string).capture(:name) > irb(main):039:1> value_val = (quoted_string | unquoted_string).capture(:value) > irb(main):040:1> literal("name=") + name_val + whitespace + > irb(main):041:1* literal("value=") + value_val > irb(main):042:1> end > => /name=((?x:'((?x:(?!\\).(?:\\{2})?\\'|(?!').)*)'|\S+))\s+value=((?x:'((?x:(?!\\).(?:\\{2})?\\'|(?!').)*)'|\S+))/ > irb(main):051:0> lines = %{ > irb(main):052:0" name='hello. I\\'m paul' value='don\\'t do that' > irb(main):053:0" name=foobar value=3 > irb(main):054:0" name='drei' value='three' > irb(main):055:0" } > irb(main):070:0> lines.scan(re) > => [["'hello. I\\'m paul'", "hello. I\\'m paul", "'don\\'t do that'", "don\\'t do that"], > ["foobar", nil, "3", nil], > ["'drei'", "drei", "'three'", "three"]] Regards, Florian Gross