You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改正则表达式((?:\w\s*)+)匹配含标点及换行的子串

正则表达式修改方案

问题说明

原正则((?:\w\s*)+)存在两个局限:无法匹配包含.、,、:、;的子串,也不支持跨行匹配带换行的内容。需要调整正则实现:

  1. 完整匹配包含上述标点及常规字符的中间内容
  2. 支持匹配带换行的跨行内容
  3. 仅当分隔符(abbaab与ccccrrru)被换行包裹时不触发匹配

修改后的正则代码

将原代码中的some_text替换为:

some_text = r"\s*((?:[\w.,:;]|\s)+?)\s*"

正则逻辑解析

  • [\w.,:;]:匹配字母、数字、下划线,以及需要支持的.、,、:、;
  • |\s:匹配任意空白字符(含换行、空格、制表符等)
  • +?:非贪婪匹配模式,确保匹配到第一个目标分隔符ccccrrru时立即停止,避免过度匹配
  • 前后的\s*:匹配中间内容首尾的任意空白(包括换行)

测试验证

无换行输入测试

import re

input_text = "cerca de abbaab como estas?. Creo yo que bien,aunque solo haya 9 de ellas pero : no estoy muy segura ccccrrru, y luego..."

some_text = r"\s*((?:[\w.,:;]|\s)+?)\s*"
regex_pattern = r"(?:abbaab)" + some_text + r"(?:ccccrrru)"

m1 = re.search(regex_pattern, input_text, re.IGNORECASE)

if m1:
    association = m1.group()
    print(repr(association))

输出结果:
' como estas?. Creo yo que bien,aunque solo haya 9 de ellas pero : no estoy muy segura '

含换行输入测试

import re

input_text = """cerca de abbaab como estas?. 
Creo yo que bien,aunque solo haya 9 de ellas. 
pero : no estoy muy segura ccccrrru, y luego...
Quizas sea."""

some_text = r"\s*((?:[\w.,:;]|\s)+?)\s*"
regex_pattern = r"(?:abbaab)" + some_text + r"(?:ccccrrru)"

m1 = re.search(regex_pattern, input_text, re.IGNORECASE)

if m1:
    association = m1.group()
    print(repr(association))

输出结果:

' como estas?. \nCreo yo que bien,aunque solo haya 9 de ellas. \npero : no estoy muy segura '

内容的提问来源于stack exchange,提问作者Matt095

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:51:36