Zed Zed - 1 year ago 46
PHP Question

Can't find a proper regex for parsing the string

So I have the string in the following format

[randomstring] [randomtest]

[randomstring] [texttext...

So the only thing in common for every line is that all text is stored inside exactly 2 square brackets per line,
. The problem is when the text goes on multiple lines:


So I'm looking for a regex to match every
pair, per line and came up with this:


As you can see, only the first line is matched and not the second. Is there a better way ?

Answer Source

You have two options. Use the s modifier to match newlines with ., or simply accept newlines inside the square brackets.

With the s modifier



Without the s-modifier



Note that I'm creating a non-capturing group with the (?:.|\n) syntax.

Also, notice that I used the non-greedy matching token ? inside the square brackets to make it stop matching when it first meets a square bracket instead of being greedy and also matching square brackets with the dot. Visualized, the ? after a quantifier (* or +) does this:

Without ?, .+ is greedy and matches until the last met ]

# Simple example: \[.+\]

With ?, .+ is non-greedy and matches only until the first met ]

# Simple example: \[.+?\]