import re
regex = re.compile(r"\b(long|anyword)\b\K[- ](?=(?:(?1))\b)", flags=re.MULTILINE)
test_str = ("Sample text:\n"
"test text long long test text\n"
"test text long long long long long long test text\n"
"test text long long test test long long long test text\n\n"
"How it should be:\n"
"test text long-long test text\n"
"test text long-long-long-long-long-long test text\n"
"test text long-long test test long-long-long test text\n\n"
"How does it work now:\n"
"test text long-long test text\n"
"test text long-long long-long long-long test text\n"
"test text long-long test test long-long long test text")
subst = "-"
result = regex.sub(subst, test_str)
if result:
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html