如何使正则表达式模式在使用 ^ 运算符时考虑行首之前的逗号?

问题描述 投票:0回答:1
import re

#example 1  with a  ,  before capture group
input_text = "Hello how are you?, dfdfdfd fdfdfdf other text. hghhg"

#example 2 without a  , (or \.|,|;|\n) before capture group
input_text = "dfdfdfd fdfdfdf other text. hghhg"

#No matter what position you place ^ within the options, it always considers it first, ignoring the others.
fears_and_panics_match = re.search(
                                    r"(?:\.|,|;|\n|^)\s*(?:(?:for|by)\s*me|)\s*(.+?)\s*(?:other\s*text)\s*(?:\.|,|;|\n)", 
                                    #r"(?:\.|,|;|\n)\s*(?:(?:for|by)\s*me|)\s*(.+?)\s*(?:other\s*text)\s*(?:\.|,|;|\n|$)", 
                                    input_text, flags = re.IGNORECASE)


if fears_and_panics_match: print(fears_and_panics_match.group(1))

为什么我使用这个模式

r"(?:\.|,|;|\n|^)\s*(?:(?:for|by)\s*me|)\s*(.+?)\s*(?:other\s*text)\s*(?:\.|,|;|\n)"
捕获
Hello how are you?, dfdfdfd fdfdfdf
无论你将
^
放在什么位置。 我需要你评估一下找到逗号
,
然后是行首的逗号
^

的可能性

每种情况下的正确输出:

#for example 1
"dfdfdfd fdfdfdf"

#for example 2
"dfdfdfd fdfdfdf"
python python-3.x regex string regex-group
1个回答
0
投票

看来您使用了错误的运算符。 另外,插入符号的意思是“开始” - 你从未指定过这个开头应该是什么,所以我疯狂猜测它需要任何字符

不知道这对你有多大帮助 - 我尽量让我的正则表达式保持愚蠢 - 让我更容易发现问题。

这适用于您提供的字符串 "[a-zA-Z0-9\s?],?\s(\w\s)*(?=other\stext)"

© www.soinside.com 2019 - 2024. All rights reserved.