2
regex = Regexp.new(/param\s*=\s*([^\|]*)/)
regex.match(text).to_s
link = $1
link.strip!

espesially code like this:

regex = Regexp.new(/regex/)
regex.match(text).to_s
match = $1

I even tried gsub misuse, but it is not The Right Way®

match = gsub Regexp.new(/.*(regex).*/, '\1')
3
  • Well, you can make the regex one character shorter: /param\s*=\s*([^|]*)/. But I don't know Ruby, so I can't tell what exactly that code does. Commented Aug 13, 2011 at 5:30
  • I try to extract data from String using regex but I am unable to do it in single line. And "[^|]" - | is special character - is it safe to ignore it? Commented Aug 13, 2011 at 5:37
  • 2
    Inside a character class, regex metacharacters don't have to be escaped (except possibly [, ], - and ^, depending on their position). Commented Aug 13, 2011 at 5:41

2 Answers 2

2

So given a string like this:

s = "blah blah param=pancakes|eggs"

You want to extract just "pancakes", right? If so, then:

you_want = s[/param\s*=\s*([^|]+)/, 1]

The \s* will eat up any leading whitespace so half of your strip! is not needed. If you don't want any whitespace inside the extracted value at all then:

you_want = s[/param\s*=\s*([^|\s]+)/, 1]

If you just want to strip off the trailing whitespace, then add an rstrip:

you_want = s[/param\s*=\s*([^|]*)/, 1].rstrip

This one will throw an exception if s doesn't your regular expression though.

See String#[] for further details.

I've also changed your []* to []+ to avoid matching nothing at all. Also, you don't have to escape most metacharacters inside a character class (see Tim's comment) so just | is fine inside a character class.

0
1
text =~ /param\s*=\s*([^|]*)/
match = $~[1]

gets the contents of the capturing group number 1 from your input string text into the variable match.

1
  • @mu: Thanks! See, I don't know Ruby :) Commented Aug 13, 2011 at 6:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.