Avba
Avba

Reputation: 15276

Ruby how to use regex to replace a part of a string and an additional part that is optional

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

Answers (1)

Tom Lord
Tom Lord

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"
  • You need to perform the gsub with a regular expression, not a String.
  • Back-slashes are added to \[ 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

Related Questions