I have a string that contains normal characters, white charsets and newline characters between <div> and </div>.
This regular expression doesn’t work: /<div>(.*)<\/div>. It is because .* doesn’t match newline characters. How can I do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You need to use the DOTALL modifier (
/s).This might not give you exactly what you want because you are greedy matching. You might instead try a non-greedy match:
You could also solve this by matching everything except ‘<‘ if there aren’t other tags:
Another observation is that you don’t need to use
/as your regular expression delimiters. Using another character means that you don’t have to escape the/in</div>, improving readability. This applies to all the above regular expressions. Here’s it would look if you use ‘#’ instead of ‘/’:However all these solutions can fail due to nested divs, extra whitespace, HTML comments and various other things. HTML is too complicated to parse with Regex, so you should consider using an HTML parser instead.