'Regex Error: A lookbehind assertion has to be fixed width [duplicate]

My pattern works in JavaScript.

(?<=(?:username|Email|URL)(?:\s|:))[^\n]+

However, when I try to use it in PHP, I get this error:

A lookbehind assertion has to be fixed width

How I can fix it?

Demo: https://regex101.com/r/x2W3S5/1



Solution 1:[1]

Use a full string match restart (\K) instead of the invalid variable-length lookbehind.

Regex 101 Demo

/^(?:username|Email|Url):? *\K\V+/mi

Make the colon and space optional by trailing them with ? or *.

Use \V+ to match the remaining non-vertical (such as \r and \n) characters excluding in the line.

See the broader canonical: Variable-length lookbehind-assertion alternatives for regular expressions


To protect your script from falsely matching values instead of matching labels, notice the use ^ with the m modifier. This will ensure that you are matching labels that occur at the start of a line.

Without a start of line anchor, Somethingelse: url whoops will match whoops.

To make multiple matches in PHP, the g pattern modifier is not used. Instead, apply the pattern in preg_match_all()

Solution 2:[2]

Sadly, js does't have regexp lookbehide. This may help you solve this: javascript regex lookbehide alternative

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
Solution 2 M.Smith