简体   繁体   English

如何在python中编写正则表达式,以选择所有以特定数字开头的字符串

[英]How do you write a regex in python which picks out all strings beginning with a specific number

I'm trying to get this regex to pick out both 7gh and 7ui but I can only get it to pick out the first one. 我正试图让此正则表达式同时选择7gh和7ui,但我只能让它选择第一个。 If anyone knows how to amend the regex such that it also picks out 7ui, I would seriously appreciate it. 如果有人知道如何修改正则表达式,使其也可以选择7ui,我将非常感谢。 I should also point out that I mean strings separated by a space. 我还应该指出,我的意思是字符串之间用空格隔开。

b = re.search(r'^7\w+','7gh ghj 7ui')
c = b.group()

Remove ^ and use findall() : 删除^并使用findall()

>>> re.findall(r'7\w+','7gh ghj 7ui')
['7gh', '7ui']

You need to remove ^ (start of string anchor) and use re.findall to find all non-overlapping matches of pattern in string : 您需要删除^ (字符串锚点的开头),然后使用re.findall查找string中模式的所有非重叠匹配项

import re
res = re.findall(r'7\w+','7gh ghj 7ui')
print(res)

See the Python demo 参见Python演示

If you need to get these substrings as whole words , enclose the pattern with a word boundary, \\b : 如果您需要将这些子字符串作为整个单词获取 ,请使用单词边界\\b将模式括起来:

res = re.findall(r'\b7\w+\b','7gh ghj 7ui')

您可能会发现不使用正则表达式会更容易

[s for s in my_string.split() if s.startswith('7')]

暂无
暂无

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

相关问题 您如何在python中编写正则表达式,以查找仅包含字母,数字和下划线的所有单词? - How do you write a regex in python that finds all word which contain only letters, numbers and underscore? 你如何在 Pyparsing 中找出哪些 ParserElements 匹配字符串? - How do you find out which ParserElements are matching strings in Pyparsing? 在Python中,如何扫描特定数字 - In Python, how do you scan for a specific number 在Python中,如何循环并仅写入特定次数的文件? - In Python, how do you loop and write to a file for only a specific number of times? 如何使用 Python 正则表达式查找 ISBN 编号的所有实例 - How do you find all instances of ISBN number using Python Regex 如何从 csv 中过滤出符合特定规则的所有行并将它们写入 Python 中的新 csv? - How do I filter all lines out of a csv that comply a specific rule and write them to a new csv in Python? 如何在Python 3中使用串联字符串创建标识符 - How do you make an identifier out of concatenated strings in Python 3 你如何对python中的字符串数字列表进行排序? - How do you sort a list of numbers which are strings in python? 你如何比较用 Python 写成字符串的数字间隔? - How do you compare number intervals, written as strings, in Python? 我试图在 python 中做一些代码,它读取一个文本文件并挑选出数字最大的 5 行并打印它们 - Im trying to do some code in python that reads a text file and picks out the 5 lines with the highest number and prints them
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM