简体   繁体   English

python使用正则表达式匹配变量文本

[英]python match variable text using regular expression

I am new to python and trying to find out how way to match a sentence with variable words 我是python的新手,正在尝试找出如何将可变词与句子匹配

for examples 'The file test.bed in successfully uploaded' 例如“文件test.bed成功上传”

Now here in the above sentence, the file name would change (it could sample.png) and rest of the words would be same. 现在,在上面的句子中,文件名将更改(可能为sample.png),其余单词将相同。

Can anybody let me know what is the best way using regular expression to match the sentence. 谁能让我知道使用正则表达式匹配句子的最佳方法是什么。

thanks 谢谢

If you just want to match anything there: 如果您只想在此匹配任何内容

r'The file (.+?) in successfully uploaded'

The . . means any character, and the + means one or more of the preceding. 表示任何字符,而+表示前面的一个或多个。

The ? ? means to do it non-greedily, so if you have two sentences in a row, like "The file foo.bar is successfully uploaded. The file spam.eggs is successfully uploaded." 意味着非贪婪地执行此操作,因此如果您连续有两个句子,例如"The file foo.bar is successfully uploaded. The file spam.eggs is successfully uploaded." , it'll match "foo.bar" , and then "spam.eggs" , rather than just finding one match "foo.bar is successfully uploaded. The file spam.eggs" . ,它会匹配"foo.bar" ,然后"spam.eggs" ,而不仅仅是找到一个匹配"foo.bar is successfully uploaded. The file spam.eggs" You may not need it in your application. 您的应用程序中可能不需要它。

Finally, the parentheses are how you mark part of a pattern as a group that you can extract from the match object. 最后,括号是将模式的一部分标记为可从匹配对象中提取的组的方式。

But what if you want to match just valid filenames? 但是,如果您只想匹配有效的文件名怎么办? Well, you'll need to come up with a rule for valid filenames, which may be different depending on your application. 好吧,您需要提出一个有效文件名的规则,该规则可能因应用程序而异。 Is it Windows-specific? 它是Windows特定的吗? Is whatever you're parsing quoting filenames with spaces? 您要解析的文件名中是否包含空格? And so on. 等等。

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

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