Chris
Chris

Reputation: 12181

Brackets/Parens in Ruby Regexp

I'm getting a warning and an error:

rubytime.rb:18: warning: character class has `[' without escape
rubytime.rb:18: unmatched ): /^(\w+).*\([([\d]+)\+]?(\d\d):(\d\d)\)\s*$/

for this line:

if line =~ /^(\w+).*\([([\d]+)\+]?(\d\d):(\d\d)\)\s*$/

I've checked a few times and the parens/brackets seem to line up, though perhaps (having recently done perl) I'm making a false assumption about Regexps in Ruby.

Upvotes: 0

Views: 464

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 37507

If you need literal brackets, you need to escape them. \[ \]. An unescaped bracket starts a "character class" such as [abc] which accepts a or b or c. These can't be nested.

Upvotes: 0

Amber
Amber

Reputation: 526493

[([\d]+)\+]?

Did you mean...

(([\d]+)\+)?

Also, [\d] is equivalent to \d, so you could really write it as...

((\d+)\+)?

If you don't want the outer group to be a matching group, you can use the non-matching (?: ):

(?:(\d+)\+)?

Upvotes: 2

Related Questions