Python 搜索此字符串并捕获名称

Python 搜索此字符串并捕获名称,python,regex,Python,Regex,我有这个密码 for f in files : ## for next file name, extract gene name using regular expression pattern ## look for ..._<gene name>_CMV... s = re.search( r'_([^_]+)_CMV', f ) ## ^^^ The part captured in parentheses is group #1 gene = s.group(1) 对于文

我有这个密码

for f in files :
## for next file name, extract gene name using regular expression pattern
## look for ..._<gene name>_CMV...
s = re.search( r'_([^_]+)_CMV', f )
## ^^^ The part captured in parentheses is group #1

gene = s.group(1)
对于文件中的f:
##对于下一个文件名,使用正则表达式模式提取基因名
##寻找。。。
s=再搜索(r''.[u^.]+)\u CMV',f)
##^^^^括号中的零件为第1组
基因=s组(1)
从字符串B4_3482_ULK4_CMV-F中提取ULK4

我正在尝试开发一个正则表达式,它可以从字符串A6_I032_5_GAR1_CMV-F中提取GAR1。到目前为止,我所尝试的似乎都不起作用

s = (r '([\W_])([^_]+)_CMV', f ) - this returns a syntax error
s = re.search (r'([^_]+)_CMV', f ) - this returns an Attribute error
       Traceback (most recent call last):
       File "protocola1.py", line 21, in <module>
       gene = s.group(1)
       AttributeError: 'NoneType' object has no attribute 'group'
s=(r'([\W_])([^]+)\u CMV',f)-这将返回语法错误
s=re.search(r'([^]+)\u CMV',f)-这将返回一个属性错误
回溯(最近一次呼叫最后一次):
文件“protocola1.py”,第21行,在
基因=s组(1)
AttributeError:“非类型”对象没有属性“组”
我感谢迄今为止所有的建议

在您的命令
(r'([\W_])([^+)\CMV',f)
中,您的
r
和字符串开头(
)之间有一个空格-这将导致语法错误。将
r
直接放在字符串开始字符的前面,这应该得到解决。

您的正则表达式
([\W])([^\u]+)\ u CMV
匹配一个非单词字符,后跟一个或多个非下划线,后跟
\u CMV

给定的测试字符串与此正则表达式不匹配,其中没有非单词字符,则结果
s
为空

改用这个:

s = re.search (r'([^_]+)_CMV', f )

这是您使用的第一个代码:

s = (r '([\W_])([^_]+)_CMV', f ) - this returns a syntax error
s = re.search (r'([\W_])([^_]+)_CMV', f)
s = re.search (r'([^_]+)_CMV', f ) - this returns an Attribute error
这是上述代码的第一个解决方案:

s = (r '([\W_])([^_]+)_CMV', f ) - this returns a syntax error
s = re.search (r'([\W_])([^_]+)_CMV', f)
s = re.search (r'([^_]+)_CMV', f ) - this returns an Attribute error
正如您在本文中看到的,上面的代码工作得非常好。在命令中,
r
和正则表达式开头之间有空格。此外,当使用此命令时,您必须使用
group(2)
,正如您在regex的附加链接中看到的那样。由于
组(1)
为您提供
(下划线)。此外,在这里您没有使用
re.search
,这可能会给您带来错误

您可以使用如下内容:

s = (r '([\W_])([^_]+)_CMV', f ) - this returns a syntax error
s = re.search (r'([\W_])([^_]+)_CMV', f)
s = re.search (r'([^_]+)_CMV', f ) - this returns an Attribute error

这是您正在使用的第二个代码:

s = (r '([\W_])([^_]+)_CMV', f ) - this returns a syntax error
s = re.search (r'([\W_])([^_]+)_CMV', f)
s = re.search (r'([^_]+)_CMV', f ) - this returns an Attribute error
这是上述代码的第二种解决方案:

s = (r '([\W_])([^_]+)_CMV', f ) - this returns a syntax error
s = re.search (r'([\W_])([^_]+)_CMV', f)
s = re.search (r'([^_]+)_CMV', f ) - this returns an Attribute error

上面的代码工作得非常好,正如您在本文中所做的那样。在您的命令中,它显示的是
AttributeError:“NoneType”对象没有属性“group”
,这无疑是
文件中确实有
值的标志。此外,当使用此命令时,您必须使用所附链接中所示的
组(1)

如果您遇到语法错误,您应该发布错误以及重现错误所需的代码。向我们展示您正在使用的代码,以及您的预期结果以解决下一个问题,
s
是一个
NoneType
,因为找不到匹配项-我建议使用诸如