Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby RegEx/pattern-match for exact word/string matching

Tags:

regex

ruby

erb

Got a quick question: I have a file like this:

ip-10-0-12-84.eu-west-1.compute.internal, master, instnum=1, Running
.....
.....
ip-10-0-26-118.eu-west-1.compute.internal, master_rabbit, instnum=4, Running
ip-10-0-26-116.eu-west-1.compute.internal, master_rabbit, instnum=5, Running
.....
ip-10-0-26-68.eu-west-1.compute.internal, sql_master, instnum=9, Running
ip-10-0-13-244.eu-west-1.compute.internal, nat, instnum=2, Running

My goal is to read the file, skipping comments (starts with #), empty/blank lines and the lines with nat or master in it. I tried this:

open('/tmp/runnings.txt').each do |line|
    next if line =~ /(^\s*(#|$)|nat|master)/

which is almost working but it also eliminates the lines with master_rabbit and sql_master in it. How can I pick only master and not the any other combination of that? Can it done in the same line? Cheers!!

like image 911
MacUsers Avatar asked Feb 14 '23 19:02

MacUsers


2 Answers

Word boundary anchors can help here:

/^\s*(#|$)|\b(nat|master)\b/
like image 189
Tim Pietzcker Avatar answered Mar 03 '23 04:03

Tim Pietzcker


open("/tmp/runnings.txt").each_line
.grep(/\A(?!\s*#)(?!.*\bnat\b)(?!.*\bmaster\b).*\S/) do |line|
  ...
end
like image 43
sawa Avatar answered Mar 03 '23 03:03

sawa