繁体   English   中英

使用正则表达式删除字母数字字符之外的数字

[英]Remove digits outside alphanumeric characters using regex

我有一个看起来像这样的字符串:

details = "| 4655748765321 | _jeffybion5                    | John Dutch                                                    |"

我想要的最终产品是这样的:

>>> details
>>> _jeffybion5 John Dutch

我当前的代码删除了所有数字,包括那些附加到字符串的数字,也忽略了两个或多个字符串之间的空格。

>>> import re
>>>
>>> details = "| 47574802757 | _jeffybion5                    | John Dutch                                                    |"
>>> details = re.sub("[0-9]", "", details)
>>> details = re.sub(" +", "", details)
>>> details = details.replace("|", " ") 
>>> details
>>> _jeffybion JohnDutch

任何有助于实现预期结果的帮助将不胜感激。

非正则表达式解决方案

一种方法:

chunks =  details.split()
res = " ".join(chunk for chunk in chunks if not chunk.isnumeric() and (chunk != "|"))
print(res)

Output

_jeffybion5 John Dutch

正则表达式解决方案

使用re.findall的替代方法:

res = " ".join(re.findall(r"\w*[a-zA-z]\w*", details))
print(res)

Output

_jeffybion5 John Dutch

第三种选择也使用re.findall

res = " ".join(re.findall(r"\w*[^\W\d]\w*", details))

图案:

[^\W\d]  

匹配任何不是数字的单词字符。

正则表达式解决方案基于您希望字符串由至少一个字母(或下划线)组成的字母和数字(也下划线)的想法。

使用您显示的确切示例,请尝试以下正则表达式。

^[^|]*\|[^|]*\|\s+(\S+)\s+\|\s+([^|]*)

这是上述正则表达式的在线演示

Python3 代码:使用 Python3x 的re模块split function 得到所需的 output。

import re
##Creating x variable here...
x="""
| 4655748765321 | _jeffybion5                    | John Dutch                                                    |
"""
##Getting required output from split function and data manipulation here. 
[x.strip(' |\||\n') for x in re.split(r'^[^|]*\|[^|]*\|\s+(\S+)\s+\|\s+([^|]*)',var) if x ][0:-1]

##Output:
['_jeffybion5', 'John Dutch']

说明:使用正则表达式^[^|]*\|[^|]*\|\s+(\S+)\s+\|\s+([^|]*)来获得所需的 output,这将创建 2 个捕获组将帮助我们稍后获取值。 然后进一步从strip命令中删除新的线或管道。 然后删除列表的最后一项,这是由拆分 function 创建的空项。

对于示例数据,您可以删除用可选空格字符包围的 pipe,并可选地删除数字后跟空格字符,直到下一个 pipe。

然后剥离周围的空间。

\s*\|\s*(?:\d+\s*\|)?

正则表达式演示

details = "| 4655748765321 | _jeffybion5                    | John Dutch                                                    |"
res = re.sub(r"\s*\|\s*(?:\d+\s*\|)?", " ", details).strip()
print(res)

Output

_jeffybion5 John Dutch

如果字符串中应该有一个 char A-Za-z,您可以拆分为| 在空白字符之间并检查它:

details = "| 4655748765321 | _jeffybion5                    | John Dutch                                                    |  | "
res = " ".join([m for m in re.split(r"\s*\|\s*", details) if re.search(r"[A-Za-z]", m)])
print(res)

Output

_jeffybion5 John Dutch

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM