python - Python如何仅当值后选择的分隔符是数字时才拆分字符串?
问题描述
我正在尝试使用 lib re 拆分字符串,并且我需要使用一些分隔符拆分值,但对于一个特定的我遇到了一些麻烦。问题是如果空格后面的下一个字符是数字,我需要拆分。例如
import re
a = 'Trying de one'
b = 'Trying de 10'
a = re.split('ate |de |do ',a)[0]
b = re.split('ate |de |do ',b)[0]
我需要的是输出:
a = 'Trying de one'
b = 'Trying de '
而且我每次都得到第二个。
解决方案
You can capture either ate
de
or do
followed by a space that you want to keep, and match 1 or more digits that you want to remove.
In the replacement use capture group 1.
import re
pattern = r"\b(ate |d[eo] )\d+";
a = 'Trying de one'
b = 'Trying de 10'
a = re.sub(pattern, r'\1', a)
b = re.sub(pattern, r'\1', b)
print(a)
print(b)
Output
Trying de one
Trying de
If you have to use split, one option is to make use of lookarounds, asserting either ate
de
or do
on the left and a digit on the right.
import re
pattern = r"(?:(?<=ate )|(?<=d[eo] ))(?=\d)"
a = 'Trying de one'
b = 'Trying de 10'
a = re.split(pattern, a)
b = re.split(pattern, b)
print(a[0])
print(b[0])
Output
Trying de one
Trying de
推荐阅读
- oracle - Oracle 在创建存储过程时出错。ORA-22905: 无法访问非嵌套表项中的行
- javascript - 在使用Javascript向表中添加行的函数中添加on-change
- flutter - 在颤动中将小部件对齐到屏幕的左侧和右侧
- sql - sql查询异常
- python - 填充pyspark数据框空值
- python - 为什么keras模型不能在python的多进程池中运行?
- java - 如何在 REST API Java 中忽略响应中的某些字段
- javascript - Javascript 自定义事件的大小是否有限?
- jquery - 使用 jQuery - ASP.NET Core MVC 通过单击按钮获取表格行的值
- swift - 在 Swift 中访问泛型参数的类型值