简体   繁体   English

拆分字母数字字符串

[英]Split alphanumeric string

I have several strings that look like 我有几串看起来像

"Abcde fgh 123,456"

I want to split it as 我想将其拆分为

["Abcde fgh", "123,456"]

I tried 我试过了

string = "Abcde fgh 123,456"
re.split(r'(\d+)', string)

But this gives 但这给

["Abcde fgh", "123", "," "456"]

You get that result because you use a capturing group with split which will also return the captured text. 之所以能得到该结果,是因为您使用了一个带有split的捕获组,该组也会返回捕获的文本。

You could use a positive lookahead instead. 您可以改用正向前瞻。 (?=\\d) would work, but to be more precise for your example data you could also use: (?=\\d)可以工作,但更精确地说,您还可以使用以下示例数据:

(?<!\\d)\\s+(?=\\d+,\\d+)

Regex demo 正则表达式演示

import re
string = "Abcde fgh 123,456"
print(re.split(r'(?<!\d)\s+(?=\d+,\d+)', string))

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

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