Patricia.
Patricia.

Reputation: 71

Why doesn't this regex match in ruby but matches in any other language?

The following works on Rubular.com but doesn't seem to match in ruby:

The string:

str = "<em>really</em>inexpensive"

Objective: Add a space after any closing tag without any space after it.

The regex:

str.gsub("/(<\/[a-zA-Z]+>)(\S)/","\1 \2")

It should give back "<em>really</em> inexpensive"

Upvotes: 2

Views: 59

Answers (1)

falsetru
falsetru

Reputation: 368954

You should use regular expression literal (/.../), not string ("..."). And escape the \ in the replacement string. (I used single-quote version of string in the following example)

str = "<em>really</em>inexpensive"
str.gsub(/(<\/[a-zA-Z]+>)(\S)/, '\1 \2') # '\1 \2' == "\\1 \\2"
# => "<em>really</em> inexpensive"

Upvotes: 6

Related Questions