Is there a way to "recall" a char sequence already matched in the regex itself?

delimiter, regex

Solution

You need something called back-reference (a very good tutorial here).

Use this regex in Python:

r'^//\[([^\]]+)\]\n\[\d+(\1\d+)*\]'

Sample run:

>>> string = """//[*#*]
... [1*#*34*#*64]"""
>>> print re.search(r'^//\[([^\]]+)\]\n\[\d+(\1\d+)*\]',string).group(0)
//[*#*]
[1*#*34*#*64]

will match your string in Python.

Debuggex Demo

Problem

The regex I'm searching has the following constraints: - it starts with "//" - then "[" a non number sequence (called delimiter in this list) and "]" - next line "\n" - "[" 0 or more number separated by the delimiter previously found "]". For example the following text matches the regex: ``` //[*#*] [1*#*34*#*64] ``` and the following text doesn't match the regex: ``` //[*#*] [1#34#64] ``` because the delimiter is not the same matched in the first row The regex I currently create is ``` ^//\[(\D)+\]\n\[[(\d)+(\D)+]*(\d)+\]$|^//\[(\D)+\]\n\[\]$|^//\[(\D)+\]\n\[(\d)+\]$ ``` but obviously this regex match with both previous examples. Is there a way to "recall" a char sequence already matched in the regex itself?

Original source