tags:

views:

47

answers:

1
+1  Q: 

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 stop after first word is read.

Any help?

+5  A: 
if (line =~ /^([HC]\d+)/)
  puts $1
end

For more info, see

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
S.Mark
To pick up all _digits_ that follow the H or C, \d+ will work. If you want it to stop on the first space, \S+.
ahh so () are necessary to get $1...$2 etc back
Akash
yeah @Akash, those round brackets are for [grouping](http://www.regular-expressions.info/brackets.html) like $1 $2 ... etc.
S.Mark
@user30997, `\d+` *will* stop on the first non-digit.
glenn jackman