aris
1
Hello,
I am trying to get a non-greedy match, but am unable to do so. What may
I be doing wrong? Please help.
======
Code:
puts
str1 = “Hi, @[Subject:13|My_Subject]”
str2 = “Hi, @[Subject:13|My_Subject], and @[Subject:45|Your_Subject]”
re = /@[Subject:\d+|(.*)]/
works fine, grabs the matching pattern
p " … this works fine …"
p str1.scan(re).flatten
why does this not grab the two patterns as an array?
how to avoid the greedy match?
that is, how to make it a non-greedy match?
puts
p " … this does not work fine; how to avoid the greedy match? …"
p str2.scan(re).flatten
puts
========
Output:
" … this works fine …"
[“My_Subject”]
" … this does not work fine; how to avoid the greedy match? …"
[“My_Subject], and @[Subject:45|Your_Subject”]
Thanks very much!
Naga V.
nrv
2
re = /@[Subject:\d+|(.*)]/
try :
re = /@[Subject:\d+|(.*?)]/
^
test :
str2.scan re
=> [[“My_Subject”], [“Your_Subject”]]
nrv
3
On Wed, Aug 29, 2012 at 3:48 AM, Regis d’Aubarede [email protected]
wrote:
re = /@[Subject:\d+|(.*)]/
try :
re = /@[Subject:\d+|(.*?)]/
test :
str2.scan re
=> [[“My_Subject”], [“Your_Subject”]]
In this case we can also use a character class which excludes closing
square bracket:
irb(main):004:0> [str1,str2].each {|s| printf “%s → %p\n”, s,
s.scan(/[Subject:\d+|([^]]*)]/)}
Hi, @[Subject:13|My_Subject] → [[“My_Subject”]]
Hi, @[Subject:13|My_Subject], and @[Subject:45|Your_Subject] →
[[“My_Subject”], [“Your_Subject”]]
irb(main):005:0> [str1,str2].each {|s| printf “%s → %p\n”, s,
s.scan(/[Subject:\d+|([^]]*)]/).flatten}
Hi, @[Subject:13|My_Subject] → [“My_Subject”]
Hi, @[Subject:13|My_Subject], and @[Subject:45|Your_Subject] →
[“My_Subject”, “Your_Subject”]
Kind regards
robert
nrv
4
Robert K. wrote in post #1073731:
On Wed, Aug 29, 2012 at 3:48 AM, Regis d’Aubarede [email protected]
wrote:
re = /@[Subject:\d+|(.*)]/
try :
re = /@[Subject:\d+|(.*?)]/
test :
str2.scan re
=> [[“My_Subject”], [“Your_Subject”]]
In this case we can also use a character class which excludes closing
square bracket:
irb(main):004:0> [str1,str2].each {|s| printf “%s → %p\n”, s,
s.scan(/[Subject:\d+|([^]]*)]/)}
Hi, @[Subject:13|My_Subject] → [[“My_Subject”]]
Hi, @[Subject:13|My_Subject], and @[Subject:45|Your_Subject] →
[[“My_Subject”], [“Your_Subject”]]
irb(main):005:0> [str1,str2].each {|s| printf “%s → %p\n”, s,
s.scan(/[Subject:\d+|([^]]*)]/).flatten}
Hi, @[Subject:13|My_Subject] → [“My_Subject”]
Hi, @[Subject:13|My_Subject], and @[Subject:45|Your_Subject] →
[“My_Subject”, “Your_Subject”]
Kind regards
robert
Excellent! Thanks very much, Robert!
Naga V.