0

How do I match the id of this escaped html string? Part of the string starts with id=\" and ends with \" In this example I need art_images_attributes_0_attachement

"<div class=\"input string optional\"><label class=\"string optional\" for=\"art_images_attributes_0_attachement\"> Attachement</label><input class=\"string optional\" id=\"art_images_attributes_0_attachement\" maxlength=\"255\" name=\"art[images_attributes][0][attachement]\" size=\"50\" type=\"text\" /></div>"
 => "<div class=\"input string optional\"><label class=\"string optional\" for=\"art_images_attributes_0_attachement\"> Attachement</label><input class=\"string optional\" id=\"art_images_attributes_0_attachement\" maxlength=\"255\" name=\"art[images_attributes][0][attachement]\" size=\"50\" type=\"text\" /></div>"

Best regards. Asbjørn Morell

2 Answers 2

1

The following regex will capture your desired outputp:

/id="([^"]*)"/

And a Rubular: http://www.rubular.com/r/dtXqK2GBPe

Note that there is not actually a \ character before the quotation marks, in Ruby the content of the string "id=\"test\"" is id="test", the \ is just there to escape any " that should be included.

And so that it will also work with escaped quotes inside of the id value, you can use this:

/id="([^"\\]*(?:\\.[^"\\]*)*)"/

http://www.rubular.com/r/b66eWno8Ce

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this was exactly what I was looking for. string.match(/id="([^"]*)"/)[1]
0

Regex-wise this would do it:

id=\\\"(.+?)\\\"

2 Comments

Nick, your example returns nil
As explained by Andrew's answer. My (naive) answer was based on the idea that I needed to match exactly what was in your question - I didn't appreciate that the \s were to be ignored.

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.