![](/img/trans.png)
[英]Python: get unknown word in a string using regex, using its boundaries
[英]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]
,但实际输出为[]
。
使用_([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!')
尝试模式: \\_([^\\_]+)\\_[^\\_\\.]+\\.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.