我无法找到一种方法来匹配字符串中的多个文件路径,同时保留字符串的其余部分。
编辑:忘记添加文件路径可能包含一个点,因此将“用户名”编辑为 user.name”
# filepath always starts with "file:///" and ends with file extension
text = """this is an example text extracted from file:///c:/users/user.name/download/temp/anecdote.pdf
1 of 4 page and I also continue with more text from
another path file:///c:/windows/system32/now with space in name/file (1232).html running out of text to write."""
我找到了许多有效的答案,但是当存在多个 filepath 时失败,并且还替换了中间的其他字符。
import re
fp_pattern = r"file:\/\/\/(\w|\W){1,255}\.[\w]{3,4}"
print(re.sub(fp_pattern, "*IGOTREPLACED*", text, flags=re.MULTILINE))
>>>"this is an example text extracted from *IGOTREPLACED* running out of text to write."
我也试过使用“在模式后找到空格后停止”,但我无法让一个工作:
fp_pattern = r"file:\/\/\/(\w|\W){1,255}\.[\w]{3,4} ([^\s]+)"
>>> 0 matches
请注意,这{1,255}
是一个贪婪的量词,会匹配尽可能多的字符,您需要在?
其后添加。
但是,仅使用惰性{1,255}?
量词并不能解决问题。您需要定义比赛应该在哪里结束。当扩展名后紧跟空格或字符串结尾时,您似乎只想匹配这些 URL。
因此,使用
fp_pattern = r"file:///.{1,255}?\.\w{3,4}(?!\S)"
查看正则表达式演示
该(?!\S)
如果排除模式将失败的任何比赛,立刻到当前位置的右边,有一个非空白字符。.{1,255}?
将匹配任何 1 到 255 个字符,尽可能少。
在 Python 中用作
re.sub(fp_pattern, "*IGOTREPLACED*", text, flags=re.S)
在re.MULTILINE
(re.M
)标志仅重定义^
和$
锚行为使其匹配开始/结束线,而不是整个字符串。该re.S
标志允许.
匹配任何字符,包括换行符。
请永远不要使用(\w|\W){1,255}?
,.{1,255}?
与re.S
标志一起使用来匹配任何字符,否则性能会下降。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句