需要定长正则表达式吗? [英] Fixed Length Regex Required?

查看:77
本文介绍了需要定长正则表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正则表达式使用向前和向后的前瞻:

  import re 
re.compile( <!inc\((?=。*?\)!>)|(?< =<!inc\(。*?)\)!>)

我正在尝试将其从C#移植到Python,但不断出现错误

 后视需要固定宽度的图案

是否有可能用Python重写而不丢失含义?



想法是让它匹配类似



的东西

 <!inc(C:\我的文档\file.jpg)!> 

更新



我正在使用环视方法来解析我修改过的HTTP多部分文本

  body = r- ---- abc 
内容处置:form-data; name = upfile; filename = file.txt
内容类型:text / plain

< ;!inc(C:\Temp\file.txt)!>
------ abc
内容处置:form-data; name = upfile2; filename = pic.png
内容类型:image / png

<!inc(C:\Temp\pic.png)!>
---- --abc
内容处置:form-data; name = note

这是一个注释
------ abc--


multiparts = re.compile(...)。split(body)

我想在进行拆分时只获取文件路径和其他文本,而不必删除开始和结束标签



代码简洁很重要,但是我愿意更改<!inc(格式,如果它使正则表达式可行。

解决方案

对于同一数组中的路径+所有内容,只需在开始和结束标记上进行分割:

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

如果说),您说自己对结束标记很灵活!> 可以出现在代码的其他位置,您可能需要考虑将结束标记更改为)!/ inc> (或其他任何东西,只要它是唯一的)即可。



查看其运行状态。


I have this regex that uses forward and backward look-aheads:

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

I'm trying to port it from C# to Python but keep getting the error

look-behind requires fixed-width pattern

Is it possible to rewrite this in Python without losing meaning?

The idea is for it to match something like

<!inc(C:\My Documents\file.jpg)!>

Update

I'm using the lookarounds to parse HTTP multipart text that I've modified

body = r"""------abc
Content-Disposition: form-data; name="upfile"; filename="file.txt"
Content-Type: text/plain

<!inc(C:\Temp\file.txt)!>
------abc
Content-Disposition: form-data; name="upfile2"; filename="pic.png"
Content-Type: image/png

<!inc(C:\Temp\pic.png)!>
------abc
Content-Disposition: form-data; name="note"

this is a note
------abc--
"""

multiparts = re.compile(...).split(body)

I want to just get the file path and other text when I do the split and not have to remove the opening and closing tags

Code brevity is important, but I'm open to changing the <!inc( format if it makes the regex doable.

解决方案

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.

这篇关于需要定长正则表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆