Python : Fixed Length Regex Required?

淺唱寂寞╮ 提交于 2019-11-27 16:29:32

For paths + "everything" in the same array, just split on the opening and closing tag:

import re
p = re.compile(r'''<!inc\(|\)!>''')
awesome = p.split(body)

You say you're flexible on the closing tags, if )!> can occur elsewhere in the code, you may want to consider changing that closing tag to something like )!/inc> (or anything, as long as it's unique).

See it run.

From the documentation:

(?<!...)

Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

(?<=...)

Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in abcdef, since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not. Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched; you will most likely want to use the search() function rather than the match() function:

Emphasis mine. No, I don't imagine you can port it to Python in it's current form.

import re

pat = re.compile("\<\!inc\((.*?)\)\!\>")

f = pat.match(r"<!inc(C:\My Documents\file.jpg)!>").group(1)

results in f == 'C:\My Documents\file.jpg'

In response to Jon Clements:

print re.escape("<!inc(filename)!>")

results in

\<\!inc\(filename\)\!\>

Conclusion: re.escape seems to think they should be escaped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!