PCRE2 (PHP>=7.3) Positive Lookbehind Regex to search for strings separated by ","

✔ Recommended Answer

Your pattern (was tagged JavaScript) only matches [1 because the negated character class [^,\]]+ can not cross matching a comma or ]

If you want the matches only, you can assert newProductsInfo: to the left followed by any character

Start the match with digits between square brackets up until either the next occurrence preceded by a comma, or the end of the string.

Using a lookbehind assertion (see the support) for it:

(?<=newProductsInfo: .*?)\[\d+].*?(?=,\[\d+]|$)

Regex demo

Edit

If you want to use PHP:

(?:newProductsInfo: \[|\G(?!^)),?\K[^,]+(?>,\h+[^,]+)*

Explanation

  • (?: Non capture group for the alternatives
    • newProductsInfo: \[ Match newProductsInfo: [
    • | Or
    • \G(?!^) Assert the current position at the end of the previous match, not at the start
  • ) Close the non capture group
  • ,?\K Match an optional comma and forget what is matched so far
  • [^,]+
  • (?>,\h+[^,]+)* Optionally repeat matching a comma, 1+ spaces and 1+ chars other than , or newline

Regex demo

To search for strings separated by commas using positive lookbehind, you can use the following regex pattern:

scss
(?<=,)[^,]+

This pattern uses a positive lookbehind assertion, (?<=,), which matches any position in the string that is immediately preceded by a comma. The [^,]+ pattern matches one or more characters that are not commas.

Here's an example usage of this regex in Python:

python
import re s = "apple,banana,orange" matches = re.findall(r"(?<=,)[^,]+", s) print(matches) # prints ['banana', 'orange']

In this example, the findall method is used to find all matches of the regex pattern in the string s. The resulting matches are the strings "banana" and "orange", which are the two strings that are separated by commas in the original string.

hbm

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755