Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中查找正则表达式_Python_Regex - Fatal编程技术网

在python中查找正则表达式

在python中查找正则表达式,python,regex,Python,Regex,我想在一个句子中找到一个与模式匹配的正则表达式,如total(10/32) ex)总数(数量)类型 例如,file.csv包含: aaaaaaaaa bbbbb cccccccccc ... total (10/32) ... dddddddddd eeeeeeeeeeee.' 如何在python中使用REGR表达式打印行 import re str= df.category items = re.findall('(total|Total)*\(\d\/\d\)', str) ite

我想在一个句子中找到一个与模式匹配的正则表达式,如
total(10/32)

ex)
总数(数量)
类型

例如,
file.csv
包含:

aaaaaaaaa bbbbb cccccccccc ... total (10/32) ... dddddddddd eeeeeeeeeeee.'
如何在python中使用REGR表达式打印行

import re 

str= df.category

items = re.findall('(total|Total)*\(\d\/\d\)', str) 
items


output []

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

[tT]otal\s*\([0-9]+/[0-9]+\)
演示

代码示例

import re

inStr = 'aaaaaaaaa bbbbb cccccccccc ... total (10/32) ... dddddddddd eeeeeeeeeeee.'
print(re.findall(r'[tT]otal\s*\([0-9]+/[0-9]+\)',inStr))
输出:

['total (10/32)']
注意事项:

['total (10/32)']
  • 务必将正则表达式模式定义为原始字符串
    r'…'
    ,以便将反斜杠保留为文字字符
  • [tT]otal\s*([0-9]+/[0-9]+\)
    将匹配以
    t
    t
    [tT]
    )开头的字符串,后跟
    otal
    ,后跟0到N个空格字符(
    \s*
    ),然后是一个
    ,1到N个数字
    ([0-9]+)
    ),一个斜杠,1到N个数字
    ([0-9]+)
    和一个右括号
您可以使用
(?i)
在regex模式中内联打开不区分大小写模式:

import re

# example text
x = 'aaaaaaaaa bbbbb cccccccccc ... total (10/32) ... dddddddddd ToTal(1/10) eeeeeeeeeeee.'

# regex pattern
ptn = r'(?i)total\s*\(\d+/\d+\)'

# check how the pattern works
re.findall(ptn, x)
#['total (10/32)', 'ToTal(1/10)']

其中:
(?模式)
用于为整个正则表达式打开列出的模式(iLmsux)。例如,您可以添加
(?ism)一些\u模式
,以打开
忽略大小写
dotall
一些\u模式的
多行
模式

关于
re.findall('[tT]otal\
,您的_字符串)
?所有乘坐普通快车的乘客:添加
flags=re.I
谢谢您的评论。^^这对me@tomy:如果我已经解决了您的问题,请毫不犹豫地接受我的回答,如中所述。谢谢。我希望找到整个列的内容,其中只包含Excel列中该列的内容,例如“total(10/32)”,并应用正则表达式。但是,仅显示其中一个内容。p=pd.read_csv('filename.csv')text=repr(p.(csv类别名称))items=re.findall'(?i)total\s*(\d+/\d+),text)items only'total(10/26)@tomy,如果使用Pandas,则
df.loc[df.category.str.contains(ptn),'category']
获取df.category中的所有文本,其中包含
total(10/26)
,其中
ptn
是我在帖子中定义的。