2

I have this regex in Ruby: http://rubular.com/r/eu9LOQxfTj

/<sometag>(.*?)<\/sometag>/im

And it successfully matches input like this:

<sometag>
  123
  456
</sometag>

Which would return

123
456

However, when I try this in javascript (testing in chrome), it doesn't match anything. Does javascript's multiline flag mean something else?

I want to capture everything non-greedily between two given tags. How can I accomplish this in javascript using regex? Here is a Debuggex Demo

<sometag>(.*?)<\/sometag>

Regular expression visualization

This is not XML parsing.

0

1 Answer 1

12

Javascript does not support multiline expressions when using . alone. You have to use [\s\S] in place of . so an example that satisfies what you want would be:

var x = "<sometag>\n\
  123\n\
  456\n\
</sometag>";

var ans = x.match(/<sometag>([\s\S]*?)<\/sometag>/im).pop();

// ans equals " 123  456"

note that you still need the m modifier.

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

5 Comments

You should explain that JS doesn't have support for the . to span across multiple lines due to not having the dotall modifier.
@hwnd good point, added the description. You should edit correct answers to improve them as opposed to just downvoting them as well.
I didn't downvote your answer, just simply left the comment.
6 years later and ([\s\S]*?) is still the best solution I found. in VSCode I've had to add the \n to make it ([\s\S\n]*?)
Very good answer worked first hand for me with the 'm' modifier

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.