Soheil
Soheil

Reputation: 5354

How to find strings in between via Regex in ruby?

I have a string like "(\n \"FOR SALE\"", so I need to use regular expression to only catch the FOR SALE value. So I used this regular expression /\"(.*?)\\/ in gsub to catch the string but I don't get any result.

"(\n    \"FOR SALE\"".gsub!("/\"(.*?)\\/",'')

But I keep getting null result.

Upvotes: 0

Views: 65

Answers (5)

bhanu
bhanu

Reputation: 2460

I think this will work specifically in your case

print "(\n    \"FOR SALE\"".match(/\"(.*)\"/)

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110675

If you want whatever is between the first two double quotes, provided there are are at least two, you could do this:

r = /
    (?<=\") # match a double quote in a positive lookbehind
    .*?     # match any number of any character, lazily
    (?=\")  # match a double quote in a positive looklookahead
    /x      # define this regex in extended mode

"(\n    \"FOR SALE\""[r] #=> "FOR SALE"

Alternatively, you could replace the positive lookbehind with \K:

r = /
    \"      # match a double quote
    \K      # forget everything matched so far
    .*?     # match any number of any character, lazily
    (?=\")  # match a double quote in a positive looklookahead
    /x      # define this regex in extended mode

Upvotes: 1

Gagan Gami
Gagan Gami

Reputation: 10251

Try this:

> s = "(\n \"FOR SALE\""
> s[/"(.*?)"/m, 1]
#=> "FOR SALE"

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

In double quoted strings, \" is the escape sequence for the double quote character ", there are not backslash in the original string.

To catch the part between the double quotes, use:

"(\n    \"FOR SALE\"".match(/"(.*?)"/)[1]
# => "FOR SALE"

Upvotes: 1

anubhava
anubhava

Reputation: 785108

There are no backslashes in original input. You can use:

print "(\n    \"FOR SALE\"".gsub!(/"(.*?)"/, '')

Output:

"(\n    " 

Or else use:

print "(\n    \\\"FOR SALE\\\"".gsub!(/\\"(.*?)\\"/, '')

Where \\\" will place \" in original input.

Upvotes: 1

Related Questions