Regular expression

hi,

puts ‘raja(dklfjdfldjkfd)gopalan(fdf)’.gsub(/((.*))/, ‘raja’)

this gives the output “rajaraja”

But I would like to have the output like raja raja gopalan(fdf)

could anyone please guide me how to write the regular expression for
this?

Google ruby greedy regexp

This gives the output you said you wanted:

puts ‘raja(dklfjdfldjkfd)gopalan(fdf)’.sub(/((\w*?))/, ’ raja ')
raja raja gopalan(fdf)

This is a great time to practice your String comparison skills. Your
Regexp is not the same as mine. Spot the difference.

hi Joel P.

Thank you . It works. I designed like

puts ‘raja(dklfjdfldjkfd)gopalan(fdf)’.sub(/((.*?))/, ’ raja ')

But it’s not working, where is the problem?

Ok thank you.

hi

puts “line1 (SS13864619). line1 (SS13864619), line3
(02).”.sub(/((\w*?))(.)((\w?))/, ‘\1\2’)

it gives the output “line1 (SS13864619). line1 (SS13864619), line3 .”

But I would like to have the output

line1 (SS13864619). line1 , line3 (02)

could you please guide me how to do that?

When you’re using Regexp to solve a problem, there’s usually more than
one input-output scenario, so you can establish a set of rules. If
there’s only one scenario then you don’t need Regexp.

Yes you are right, but my problem is, each and every time the numbers
inside the bracket would vary, So I need regular expression for
that,isn’t it?

line1 (SS13864619) must have been removed. Output would be,

line1 , line3 (02).

If that’s all that varies:

irb(main):009:0> s.sub(/(\Aline1 (SS\d+). line1 )((SS\d+))/, ‘\1’)
=> “line1 (SS13864619). line1 , line3 (02).”