如何编写正则表达式,实现句号后紧跟大写字母时分割字符串
正则分割解决方案
需求说明
- 分割规则:当字符串中的句号「.」后紧跟A-Z范围的大写英文字母时,在该句号后执行分割
- 分割过程保留原字符串的所有内容,不会丢失句号或后续的大写字母
核心正则表达式
使用零宽断言匹配正确的分割位置,表达式如下:/(?<=\.)(?=[A-Z])/
正则逻辑解释
(?<=\.):正向后行断言,限定匹配位置的前一个字符必须是句号(?=[A-Z]):正向先行断言,限定匹配位置的后一个字符必须是大写英文字母
两个断言组合后匹配到的是句号和大写字母之间的空位置,在该位置分割即可完全符合需求。
代码示例(Python为例)
import re # 待处理原始字符串 raw_str = "Cryptocurrency prices today were trading mixed with the world's largest cryptocurrency by market capitalization trading marginally lower. Cryptocurrency prices today were trading mixed with the world's largest cryptocurrency by market capitalization trading marginally lower. Bitcoin prices today were down 0.9% at $61,693. It is up 112% this year so far after hitting a record high of near $67,000 in October.Ether prices climbed to record high during the weekend. The AUM included all-time highs for individual asset products such as $55.2 billion for bitcoin products (52.2% increase) and $15.9 billion for ethereum products (30.0% increase)." # 分割后对每个子串去首尾空格,再用换行拼接得到最终结果 result = '\n'.join([i.strip() for i in re.split(r'(?<=\.)(?=[A-Z])', raw_str)]) print(result)
输出结果
Cryptocurrency prices today were trading mixed with the world's largest cryptocurrency by market capitalization trading marginally lower. Cryptocurrency prices today were trading mixed with the world's largest cryptocurrency by market capitalization trading marginally lower. Bitcoin prices today were down 0.9% at $61,693. It is up 112% this year so far after hitting a record high of near $67,000 in October. Ether prices climbed to record high during the weekend. The AUM included all-time highs for individual asset products such as $55.2 billion for bitcoin products (52.2% increase) and $15.9 billion for ethereum products (30.0% increase).
内容的提问来源于stack exchange,提问作者Gautam Jha
相关产品推荐
相关产品推荐

