Reputation: 15276
I am parsing strings in a log file, formatted in one of the following ways:
[info] something written here
or
[info] - something written here
In both cases, I need to return the:
something written here
The -
is an optional addition to the log I am parsing.
I would like to have one regex to get the same result in both cases
I have tried:
line = "[info] - something written here"
line.gsub('[info] ',"")
Which results in
- something written here
How can I get rid of the optional -
?
Upvotes: 0
Views: 69
Reputation: 28305
line1 = "[info] something written here"
line2 = "[info] - something else written here"
line1.gsub(/\[info\] (- )?/,"") #=> "something written here""
line2.gsub(/\[info\] (- )?/,"") #=> "something else written here"
gsub
with a regular expression, not a String
.\[
and \]
to use the literal characters, rather than as brackets for a regex character set.?
makes the capture group optional.You could also consider making the pattern even more generic - e.g. to say "any number of spaces and hyphens": /\[info\][- ]*/
Upvotes: 1