为什么在Python原串的正则表达式中需要添加DOTALL来匹配换行符

-2 投票
2 回答
3834 浏览
提问于 2025-04-17 23:39

为什么在Python的正则表达式中,需要添加DOTALL标志才能匹配包括换行符在内的字符呢?我问这个是因为原始字符串本来应该忽略像换行符这样的特殊字符的转义。根据文档:

解决办法是使用Python的原始字符串表示法来写正则表达式模式;在以'r'开头的字符串中,反斜杠不会以任何特殊方式处理。所以r"\n"是一个包含两个字符的字符串,分别是'\'和'n',而"\n"是一个包含一个字符的字符串,表示换行。

这是我的情况:

string = '\nSubject sentence is:  Appropriate support for families of children diagnosed with hearing impairment\nCausal Verb is :  may have\npredicate sentence is:  a direct impact on the success of early hearing detection and intervention programs in reducing the negative effects of permanent hearing loss'

re.search(r"Subject sentence is:(.*)Causal Verb is :(.*)predicate sentence is:(.*)", string ,re.DOTALL)

这样可以匹配成功,但是当我去掉DOTALL标志时,就没有匹配了。

2 个回答

2

在正则表达式中,.代表的是除了换行符\n以外的任何字符

所以如果你的字符串里面有换行符,使用.*就无法匹配到这个换行符\n

但是在Python中,如果你使用re.DOTALL这个标志(也叫re.S),那么这个点.就会把换行符\n也算进去。

1

你的源字符串不是原始的,只有你的模式字符串是原始的。

可以试试

string = r'\n...\n'
re.search("Subject sentence is:(.*)Causal Verb is :(.*)predicate sentence is:(.*)", string)

撰写回答