如何获取字符串中任何整数之前的每个字符



如果我有一个字符串,看起来像这样:

hello my name is12345 blah blah things

另一个看起来像这样的:

slim shady4321 oooh la la

如何只获取整数前面的字符?

循环字符串中的所有字符并检查该字符是否为整数,然后中断循环的最佳方法是什么?

您可以使用以下正则表达式:

^D*

说明:

^:开始符号(确保从字符串的开头开始匹配(D*:非数字字符的序列。

(假设在您的示例中,您只想检索hello my name isslim shady(。

您可以使用正则表达式来解决问题(同时使用来自用户ctwheels的搜索模式(

import re
pattern = 'D+(?=d)'
string1 = 'hello my name is12345 blah blah things'
string2 = 'slim shady4321 oooh la la'
match = re.search(pattern, string1)
match.group(0)

将返回

'hello my name is'

您可以使用积极的前瞻性。匹配数字前的所有非数字字符。

D*(?=d)

我会追求简单:

s = "hello my name is12345 blah foo432423 blah things"
words = s.split(' ')
for word in words:
if not word.isalpha():
print(word.rstrip('0123456789'))

这会将字符串拆分为多个单词,并检查每个单词是否只包含字母。如果不是(我们正在寻找的(,我们将使用该单词并删除尾随数字。给你:

is
foo

没有正则表达式,没有导入,只有简单的内置类。

s = 'hello my name is12345 blah blah things'
ss = 'slim shady4321 oooh la la'
w = ''
for c in ss:                                 # OR use the below
if str(c).isalpha() or str(c).isspace(): # if not str(c).isdigit():
w += c
else:
break;
print(w)

输出:

hello my name is
slim shady