Is it possible to make this ruby regex code shorter?
regex = Regexp.new(/param\s*=\s*([^\|]*)/)
regex.match(text).to_s
link = $1
link.strip!
espesially code like this:
regex = Re开发者_如何学Cgexp.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')
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.
text =~ /param\s*=\s*([^|]*)/
match = $~[1]
gets the contents of the capturing group number 1 from your input string text into the variable match.
加载中,请稍侯......
精彩评论