1

If I have a string that is this

<f = x1106f='0'>something

and The values inside <> can change How would I use regular expressions to isolate "something" and replace the tag?

EDIT:

<(.*?)> Pattern worked
3
  • A lot of people are going to tell you to not parse HTML yourself. You almost always want to use something robust like Nokogiri. Commented Sep 20, 2013 at 3:39
  • @Max it's not really "parsing" but merely extracting a value from a specific tag. Commented Sep 20, 2013 at 3:48
  • @alfasin with questions like this it's hard to tell if this is an isolated string extraction problem where regexs are appropriate, or if they've already torn apart a larger document with regexs and string methods and they're stuck on this one part. Commented Sep 20, 2013 at 16:21

2 Answers 2

1

What you need is

string =~ />([^<]+)/

and the something will be captured in $1.

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

Comments

0

Use the following regex to capture "something":

(?<=>)(.*?)(?=<)

assuming that after "something" there's a closing tag.

Link to fiddle

6 Comments

Downvoting without commenting is lame!
I didn't downvote, but for the sake of efficiency, the lookbehind and lookahead are unnecessary here with your capture group. Your regexp is looking for anything that follows a > and precedes a </. However, this regexp would provide the same match: >(.*)<\/. Also, the .* would be overly greedy - a .*? is safer - or even better [^<]* (e.g. if the string were <f = x1106f='0'>something</f><f = asdf>somethingelse</f>, the match would be something</f><f = asdf>somethingelse).
@ChicagoRedSox thanks for your comment - I changed the regex (and fiddle) to support the scenario you showed. The reason I'm using lookaround is tin order to have a group-match which can be referred and used later on in the code.
Oh OK - yeah if you're intending to capture the lookaround than that makes sense
@ChicagoRedSox I wasn't sure but that's what I understood from "use regular expressions to isolate "something" and replace the tag?"
|

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.