Substring from regexp

Discussion in 'Ruby' started by Eduardo Yáñez Parareda, Jun 15, 2006.

  1. Hi all,

    how could I get a substring which match a regular expression?

    I mean:

    "assddHellOasddaffer".something(/^H.*O$) => HellO
     
    Eduardo Yáñez Parareda, Jun 15, 2006
    #1
    1. Advertisements

  2. "assddHellOasddaffer"[/H.*O/]

    lopex
     
    Marcin Mielżyński, Jun 15, 2006
    #2
    1. Advertisements

  3. "assddHellOasddaffer"[/H.*O/]

    Thanks, I'm newbie with Ruby but with regexps too!

    Well, another question. Having this string


    "fsdfadfdsf{1dffsdfadsf-}fsdfdsfa{1fsdfsdfsdfsdfsdh-}f"

    if I split it with /1\{.*-\}/ I get:

    ["fsdfadfdsf", "f"]

    that's right, but I want to get ["{1dffsdfadsf-}", "{1fsdfsdfsdfsdfsdh-}"] that's said, the inverse of split.
    Might I change the regexp or is there any method I could use?
     
    Eduardo Yáñez Parareda, Jun 15, 2006
    #3
  4. "assddHellOasddaffer".match(/(H.+O)/)
    Yes, I realized that after reading Marcin's answer...
     
    Eduardo Yáñez Parareda, Jun 15, 2006
    #4
  5. Sure? I'd rather guess that you want three strings.
    You want #scan:

    irb(main):003:0>
    "fsdfadfdsf{1dffsdfadsf-}fsdfdsfa{1fsdfsdfsdfsdfsdh-}f".scan /\{[^}]*\}/
    => ["{1dffsdfadsf-}", "{1fsdfsdfsdfsdfsdh-}"]
    irb(main):004:0>
    "fsdfadfdsf{1dffsdfadsf-}fsdfdsfa{1fsdfsdfsdfsdfsdh-}f".scan /\{.*?\}/
    => ["{1dffsdfadsf-}", "{1fsdfsdfsdfsdfsdh-}"]
    irb(main):005:0>
    "fsdfadfdsf{1dffsdfadsf-}fsdfdsfa{1fsdfsdfsdfsdfsdh-}f".scan /\{[^}]*?\}/
    => ["{1dffsdfadsf-}", "{1fsdfsdfsdfsdfsdh-}"]

    Kind regards

    robert


    PS: It's usually better to post new questions to new threads.
     
    Robert Klemme, Jun 15, 2006
    #5
  6. You want #scan:

    Yes!, I tried it before post this message but may be with wrong regexp :(
    I'm sorry , better next time. Thanks a lot.
     
    Eduardo Yáñez Parareda, Jun 15, 2006
    #6
  7. "fsdfadfdsf{1dffsdfadsf-}fsdfdsfa{1fsdfsdfsdfsdfsdh-}f".scan /\{.*?\}/
    I think I'm bit tedious but why it doesn't work if I put some \n inside source string?
    Is '\n' character not considered when using '.*' expression?
     
    Eduardo Yáñez Parareda, Jun 15, 2006
    #7
  8. use multiline option:

    /.../m

    lopex
     
    Marcin Mielżyński, Jun 15, 2006
    #8
    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.