Printing part what's found with a regex

J

John Smith

Hi everyone,

I'm trying to build a program that filters
certain lines through regular expressions.
In the seconde regular expression I wan to
be able to print only what's within the
\(\w+\) part of the expression?

How do I do this?

counter = 0
if inFile.nil? == false
File.foreach(inFile) do |line|
if line =~ /^[^%\s*^%]/
if line =~ /(?!%)\w+\s+\(\w+\)/
puts "found in line #{counter+1} "
puts line
end
end
counter = counter + 1
end
end

Regards,
Ted.
 
J

Jonathan Nielsen

[Note: parts of this message were removed to make it a legal post.]

You will find that portions of the regex marked with parentheses will be
places in variables called $1, $2, etc. So, you will want to change the
regex to

/(?!%)\w+\s+(\(\w+\))/

And then the contents of (\(\w+\)) will be placed in the variable $2.

-Jonathan Nielsen
 
J

John Smith

Jonathan said:
You will find that portions of the regex marked with parentheses will be
places in variables called $1, $2, etc. So, you will want to change the
regex to

/(?!%)\w+\s+(\(\w+\))/

And then the contents of (\(\w+\)) will be placed in the variable $2.

-Jonathan Nielsen

hmm I'm trying to print this variable
but I get nothing. I've tried:

puts "#$2"
puts "#{$2}"
 
J

John Smith

John said:
hmm I'm trying to print this variable
but I get nothing. I've tried:

puts "#$2"
puts "#{$2}"

Ah just realized it is in variable $1.
(?!%) is a look ahead so I guess it doesn't count as a group?
 
J

Jonathan Nielsen

[Note: parts of this message were removed to make it a legal post.]

Ah just realized it is in variable $1.
(?!%) is a look ahead so I guess it doesn't count as a group?

Ah yes, that'll be it. Sorry, I wasn't paying attention to what was inside
that first group. Glad you got it figured out.

-Jonathan Nielsen
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top