0

I need to write a regex for the following text:

"How can you restate your point (something like: \"<font>First</font>\") as a clear topic?"

that keeps whatever is between the

\" \"

characters (in this case <font>First</font>

I came up with this:

/"How can you restate your point \(something like: |\) as a clear topic\?"/

but how do I get ruby to remove the unwanted surrounding text and only return <font>First</font>?

1
  • A regex does not keep anything; a regex does not do anything. It is just an object. A method (that uses a regex) may do something, as well as keep something. Commented Jul 20, 2017 at 19:24

3 Answers 3

2

lookbehind, lookahead and making what is greedy, lazy.

 str[/(?<=\").+?(?=\")/] #=> "<font>First</font>"
Sign up to request clarification or add additional context in comments.

2 Comments

s[/"([^"]+)"/, 1] version looks tidier to me.
@WiktorStribiżew I agree. That's so good that I shan't forget it.
0

If you have strings just like that, you can .split and get the first:

> str.split(/"/)[1]
=> "<font>First</font>"

1 Comment

..or str.split('"')[1]. Personally, I only use a regex when a string won't do.
0

You certainly can use a regular expression, but you don't need to:

str = "How can you restate (like: \"<font>First</font>\") as a clear topic?"

str[str.index('"')+1...str.rindex('"')]
  #=> "<font>First</font>"

or, for those like me who never use three dots:

str[str.index('"')+1..str.rindex('"')-1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.