regular expression help please

Discussion in 'Ruby' started by Paul, May 29, 2004.

  1. Paul

    Paul Guest

    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'

    I know it has to do with \0 \1 etc, but cant figure out how to make
    the re work for both cases

    Thanks
     
    Paul, May 29, 2004
    #1
    1. Advertisements

  2. 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:
    Regards,
    Florian Gross
     
    Florian Gross, May 29, 2004
    #2
    1. Advertisements

  3. You could do:

    lines = <<'EOF'
    name=paul value=10 otherstuff=123
    name='hello paul' value='10' otherstuff='123'
    name='hello paul, it\'s nice here' value='10' otherstuff='123'
    name='hello paul, don't do that' value='10' otherstuff='123'
    EOF

    lines.scan( %r{
    (name|value|otherstuff)
    =
    (?: '((?:[^'\\]|\\')*)' | (\S+) )
    }x ) do |m|
    key = m[0]
    val = (m[1]||m[2]).gsub(/\\(.)/, '\\1')
    puts "key=#{key}"
    puts "value='#{val}'"
    end

    $ ./sc.rb
    key=name
    value='paul'
    key=value
    value='10'
    key=otherstuff
    value='123'
    key=name
    value='hello paul'
    key=value
    value='10'
    key=otherstuff
    value='123'
    key=name
    value='hello paul, it's nice here'
    key=value
    value='10'
    key=otherstuff
    value='123'
    key=name
    value='hello paul, don'
    key=value
    value='10'
    key=otherstuff
    value='123'

    Of course you can replicate the expression to cover all three x=y pairs.

    Regards

    robert
     
    Robert Klemme, May 29, 2004
    #3
  4. Paul

    Paul Guest

    Thanks guy this is great.

    Where would I find Regexp::English ? is it a module in the RAA?

    Thanks

    Paul
     
    Paul, May 31, 2004
    #4
  5. I'm planning to release it Real Soon Now. Still thinking about what of
    the more advanced features should be in the final release and which
    shouldn't.

    Until then I'll just keep using it to solve other persons problem when
    the situation demands it. :)
    No problem, glad I could help!

    Regards,
    Florian Gross
     
    Florian Gross, May 31, 2004
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.