繁体   English   中英

在python中使用正则表达式单词边界提取单词形式字符串

[英]Extract word form string using regex word boundaries in python

假设我有一个这样的文件名,并且想在Python中将其一部分提取为字符串。

import re
fn = "DC_QnA_bo_v.15.12.3_DE_duplicates.xlsx"
rgx = re.compile('\b_[A-Z]{2}\b')
print(re.findall(rgx, fn))

预期输出为[DE] ,但实际输出为[]

你可以用

(?<=_)[A-Z]+(?=_)

这利用了双方的环顾四周,请参阅regex101.com上的演示 为了获得更严格的结果,您需要指定更多示例输入。

使用_([AZ]{2})

例如:

import re
fn = "DC_QnA_bo_v.15.12.3_DE_duplicates.xlsx"
rgx = re.compile('_([A-Z]{2})')
print(rgx.findall(fn))           #You can use the compiled pattern to do findall. 

输出:

['DE']

您想要的输出似乎是DE ,它的左右两侧是两个_ 此表达式也可能起作用:

# -*- coding: UTF-8 -*-
import re

string = "DC_QnA_bo_v.15.12.3_DE_duplicates.xlsx"
expression = r'_([A-Z]+)_'
match = re.search(expression, string)
if match:
    print("YAAAY! \"" + match.group(1) + "\" is a match 💚💚💚 ")
else: 
    print('🙀 Sorry! No matches!')

产量

YAAAY! "DE" is a match 💚💚💚

或者,如果需要,可以添加2数量词:

# -*- coding: UTF-8 -*-
import re

string = "DC_QnA_bo_v.15.12.3_DE_duplicates.xlsx"
expression = r'_([A-Z]{2})_'
match = re.search(expression, string)
if match:
    print("YAAAY! \"" + match.group(1) + "\" is a match 💚💚💚 ")
else: 
    print('🙀 Sorry! No matches!')

在此处输入图片说明

DEMO

尝试模式: \\_([^\\_]+)\\_[^\\_\\.]+\\.xlsx

说明:

\\_ _从字面上匹配_

[^\\_]+ -带+运算符的否定字符类:匹配_以外的一个或多个字符

[^\\_\\.]+ -与上面相同,但是这次匹配的字符不是_.

\\.xlsx .xlsx从字面上匹配.xlsx

演示

这个想法是在扩展名.xlsx之前匹配最后一个模式_something_

您可以使用正则表达式( re模块)进行显示,但是可以通过以下方式不使用任何import来完成:

fn = "DC_QnA_bo_v.15.12.3_DE_duplicates.xlsx"
out = [i for i in fn.split('_')[1:] if len(i)==2 and i.isalpha() and i.isupper()]
print(out) # ['DE']

说明:我在_处分割fn ,然后丢弃第一个元素和过滤器元素,因此仅保留长度2的str s,该长度由字母组成,由大写字母组成。

另一种re的解决方案:

rgx = re.compile('_([A-Z]{1,})_')
print(re.findall(rgx, fn))

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM