RegEx Help in Ruby
My sample file is like below:
H343423 Something1 Something2
C343423 0
A23423432 asdfasdf sdfs
#2342323
I have the following regex:
if (line =~ /^[HC]\d+\s/) != nil
puts line
end
Basically I want to read everything that starts with H or C and is followed by numbers and I want to stop reading when space is encountered (I want to read one word).
Output I want is:
H343423
C343423
Output my RegEx is getting is:
H343423 Something1 Something2
C343423 0
So it is fetching the whole line but I just want it to开发者_如何学JAVA stop after first word is read.
Any help?
if (line =~ /^([HC]\d+)/)
puts $1
end
For more info, see
- Use Round Brackets for Grouping
If you don't want to use brackets, there is special variable for the match item $&
Following will do the same
if line =~ /^[HC]\d+/
puts $&
end
精彩评论