user1134991
user1134991

Reputation: 3103

How to get three consecutive backslashes in Regexp

I want to create a regular expression such as:

/\\\s*\\\s*$/

I am trying it in this way:

Regexp.new('\\\s*\\\s*$') # => /\\s*\\s*$/

What am I doing wrong?

Upvotes: 0

Views: 134

Answers (2)

hwnd
hwnd

Reputation: 70732

Well (\\) matches a single backslash. Backslash serves as an escape character for Regexp.

rgx = Regexp.new('\\\\\\s*\\\\\\s*$')

A more verbose way of doing this would be the following as @Cary Swoveland stated.

rgx = Regexp.new('\\{3}s*\\{3}s*$')

Upvotes: 4

Max
Max

Reputation: 22365

Using literal notation avoids some confusion. This compiles to what you said you want:

/\\\s*\\\s*$/

Though, to be clear, this still matches a single backslash, optional whitespace a single backslash and more optional whitespace. Backslashes are escaped when you inspect a regexp.

Upvotes: 1

Related Questions