简体   繁体   English

python regex匹配文件名但不显示

[英]python regex to match file name but get None

I have a few files in the folder and I want to find out the content and match its file name. 我的文件夹中有几个文件,我想找出内容并匹配其文件名。 But when I use re.search to achieve my goal I can only get 'None'. 但是,当我使用re.search实现我的目标时,我只会得到“无”。 Anyone could help? 有人可以帮忙吗?

import re
xe = r'D:\ABC\cc123.xml'
re.search('cc*?.xml', xe)

(Though there is an accepted answer, I don't feel the answer is clear for other people, and there is still room to improve, so I added a new answer here) (尽管有一个可接受的答案,但我认为答案对于其他人来说并不明确,并且仍有改进的余地,因此我在此处添加了一个新答案)

The problem is simply OP is using a wrong regex: cc*?.xml 问题是OP只是使用了错误的正则表达式: cc*?.xml

* means any occurrence of the preceding token (which means c in your case) *? *表示前面的标记是否出现(在您的情况下为c*? is a reluctant match any occurrence. 是不愿意匹配的任何情况。 . means any character 表示任何字符

Which means what you are trying to do is match a string which is: 这意味着您要尝试匹配的字符串是:

  • a c c
  • followed by any occurrence of c 随后出现任何c
  • followed by any character 跟任何字符
  • followed by xml 其次是xml

Example of matching strings are c.xml ccccccAxml etc. 匹配字符串的示例是c.xml ccccccAxml等。

What you were trying to do, I believe is 我想你想做的是

cc.*?\.xml

which means matching 这意味着匹配

  • cc
  • .*? : followed by any occurrence of any character, matching as few as possible :后跟出现任何字符,尽可能少地匹配
  • \\. : followed by a dot (note the difference of \\. vs . ) :后跟一个点(请注意\\..的区别)
  • followed by xml 其次是xml

How about something like this with a small tweak? 稍微调整一下,这样的东西怎么样?

import re
xe = 'D:\ABC\cc123.xml'
print (re.search('cc.*?.xml', xe).group())

output: 输出:

cc123.xml

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

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