'How to make dot match newline characters using regular expressions

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?



Solution 1:[1]

You need to use the DOTALL modifier (/s).

'/<div>(.*)<\/div>/s'

This might not give you exactly what you want because you are greedy matching. You might instead try a non-greedy match:

'/<div>(.*?)<\/div>/s'

You could also solve this by matching everything except '<' if there aren't other tags:

'/<div>([^<]*)<\/div>/'

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 '/':

'#<div>([^<]*)</div>#'

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.

Solution 2:[2]

To match all characters, you can use this trick:

%\<div\>([\s\S]*)\</div\>%

Solution 3:[3]

You can also use the (?s) mode modifier. For example,

(?s)/<div>(.*?)<\/div>

Solution 4:[4]

There shouldn't be any problem with just doing:

(.|\n)

This matches either any character except newline or a newline, so every character. It solved it for me, at least.

Solution 5:[5]

An option would be:

'/<div>(\n*|.*)<\/div>/i'

Which would match either newline or the dot identifier matches.

Solution 6:[6]

There is usually a flag in the regular expression compiler to tell it that dot should match newline characters.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 Peter Mortensen
Solution 3 Peter Mortensen
Solution 4 Peter Mortensen
Solution 5 MillerMedia
Solution 6 pau.estalella