将匹配项从正则表达式合并为单个列表

发布于 2025-02-11 01:12:01 字数 513 浏览 1 评论 0原文

我正在尝试将骆驼中的字符串分离为单个列表,

我设法将单词用正则表达式分开

,但是我对如何创建我尝试串联列表的所有匹配的单个列表毫无意义

,但我不喜欢这样``认为它在我的情况下会起作用

n="SafaNeelHelloAByeSafaJasleen"
patt=re.compile(r'([A-Z][a-z]*|[a-z$])')
matches=patt.finditer(n)
for match in matches:
    a=match.group()
    list=a.split()
    print(list)

['Safa']

['Neel']

['Hello']

['A']

['Bye']

['Safa']

['Jasleen']

所需的输出:

['Safa','Neel','Hello','A','Bye','Safa','Jasleen']

I am trying to separate a string in CamelCase into a single list

I managed to separate the words with regular expressions

But I am clueless on how create a single list of all the matches

I tried to concatenate the lists, append something like that but I don't think it would work in my case

n="SafaNeelHelloAByeSafaJasleen"
patt=re.compile(r'([A-Z][a-z]*|[a-z$])')
matches=patt.finditer(n)
for match in matches:
    a=match.group()
    list=a.split()
    print(list)

output:

['Safa']

['Neel']

['Hello']

['A']

['Bye']

['Safa']

['Jasleen']

Desired output:

['Safa','Neel','Hello','A','Bye','Safa','Jasleen']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

在你怀里撒娇 2025-02-18 01:12:01

您正在寻找re.findall(),而不是re.finditer()

>>> string = "SafaNeelHelloAByeSafaJasleen"
>>> pattern = re.compile(r"([A-Z][a-z]*|[a-z$])")
>>> pattern.findall(string)
['Safa', 'Neel', 'Hello', 'A', 'Bye', 'Safa', 'Jasleen']

You're looking for re.findall(), not re.finditer():

>>> string = "SafaNeelHelloAByeSafaJasleen"
>>> pattern = re.compile(r"([A-Z][a-z]*|[a-z$])")
>>> pattern.findall(string)
['Safa', 'Neel', 'Hello', 'A', 'Bye', 'Safa', 'Jasleen']
那一片橙海, 2025-02-18 01:12:01

您可以将匹配项附加到新列表:

new_list=[]
for match in matches:
    a=match.group()
    new_list.append(a)

new_list的输出:

['Safa', 'Neel', 'Hello', 'A', 'Bye', 'Safa', 'Jasleen']

You can append the matches to new list:

new_list=[]
for match in matches:
    a=match.group()
    new_list.append(a)

Output of new_list:

['Safa', 'Neel', 'Hello', 'A', 'Bye', 'Safa', 'Jasleen']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文