我不知道爲什麼你會使用負向視向。你是說在換行之前你最多需要10個字。下面的正則表達式應該可以工作。它使用積極的lookahead來確保是之後的換行字。當搜索單詞時,使用`b \ w + \ b`而不是你正在使用的。
/(\b\w+\b)*(?=.*\\n)/
的Python:
result = re.findall(r"(\b\w+\b)*(?=.*\\n)", subject)
說明:
# (\b\w+\b)*(?=.*\\n)
#
# Match the regular expression below and capture its match into backreference number 1 «(\b\w+\b)*»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Note: You repeated the capturing group itself. The group will capture only the last iteration. Put a capturing group around the repeated group to capture all iterations. «*»
# Assert position at a word boundary «\b»
# Match a single character that is a 「word character」 (letters, digits, etc.) «\w+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Assert position at a word boundary «\b»
# Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=.*\\n)»
# Match any single character that is not a line break character «.*»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Match the character 「\」 literally «\\»
# Match the character 「n」 literally «n»
您也不妨考慮一個事實,即有可能是你的字符串中沒有\ n。
你可以編輯你的問題,包括更多的例子嗎?下面的討論讓我很困惑,關於你想要達到的目標。 – N3dst4