Max
Max

Reputation: 629

Ruby regexp doesn't work with double quote string?

regexp = /(?:status\\\":)(\d*)(?:\,)/
string = '\n{\"status\":80,\"message\":\"Test message\"}\n'
result = string.scan(regexp)[0]
puts result

Why does this work, but if I do

regexp = /(?:status\\\":)(\d*)(?:\,)/
string = "\n{\"status\":80,\"message\":\"Test message\"}\n"
result = string.scan(regexp)[0]
puts result

I get no results? The string I'm searching is copied from a Mechanize body result. I'm trying to use this same regexp on the direct result of a mechanize page object, and no matches are showing, I'm assuming for the same reason this issue is happening.

Upvotes: 2

Views: 1129

Answers (2)

pguardiario
pguardiario

Reputation: 55012

You want to use JSON for that:

JSON.parse(string)['status']
#=> 80

Upvotes: 1

tadman
tadman

Reputation: 211740

The problem here is that '\n' and "\n" are not the same thing:

'\n'
#=> "\\n" literal-backslash n

"\n"
# => "\n" newline character

If you need the backslash codes to work, you need double-quoted strings.

Don't forget about things like %q[...] and %Q[...] as alternatives to using quotes if both types are used in your string and you don't want to escape them.

Upvotes: 2

Related Questions