python - 如何在 PyParsing 中构造一个相当于 FollowedBy 子类的 "leading"

标签 python pyparsing

我正在尝试使用 PyParsing 删除前导或尾随空白字符来清理一些代码。删除前导空格非常容易,因为我可以使用 FollowedBy 子类来匹配字符串但不包含它。现在我需要同样的东西来处理我的识别字符串后面的内容。

这里是一个小例子:

from pyparsing import *

insource = """
annotation (Documentation(info="  
  <html>  
<b>FOO</b>
</html>  
 "));
"""
# Working replacement:
HTMLStartref = OneOrMore(White(' \t\n')) + (FollowedBy(CaselessLiteral('<html>')))

## Not working because of non-existing "LeadBy" 
# HTMLEndref = LeadBy(CaselessLiteral('</html>')) + OneOrMore(White(' \t\n')) + FollowedBy('"')

out = Suppress(HTMLStartref).transformString(insource)
out2 = Suppress(HTMLEndref).transformString(out)

作为输出,得到:

>>> print out
annotation (Documentation(info="<html>
<b>FOO</b>
</html>
 "));

并且应该得到:

>>> print out2
annotation (Documentation(info="<html>
<b>FOO</b>
</html>"));

我查看了documentation但找不到与 FollowedBy 等效的“LeadBy”或实现该目标的方法。

最佳答案

您要求的是类似“lookbehind”的内容,即仅当某些内容前面有特定模式时才匹配。目前我还没有一个明确的类,但是对于你想做的事情,你仍然可以从左到右转换,只保留前导部分,而不是抑制它,只是抑制空格.

以下是解决您的问题的几种方法:

# define expressions to match leading and trailing
# html tags, and just suppress the leading or trailing whitespace
opener = White().suppress() + Literal("<html>")
closer = Literal("</html>") + White().suppress()

# define a single expression to match either opener
# or closer - have to add leaveWhitespace() call so that
# we catch the leading whitespace in opener
either = opener|closer
either.leaveWhitespace()

print either.transformString(insource) 


# alternative, if you know what the tag will look like:
# match 'info=<some double quoted string>', and use a parse
# action to extract the contents within the quoted string,
# call strip() to remove leading and trailing whitespace,
# and then restore the original '"' characters (which are
# auto-stripped by the QuotedString class by default)
infovalue = QuotedString('"', multiline=True)
infovalue.setParseAction(lambda t: '"' + t[0].strip() + '"')
infoattr = "info=" + infovalue

print infoattr.transformString(insource)

关于python - 如何在 PyParsing 中构造一个相当于 FollowedBy 子类的 "leading",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11774840/

相关文章:

python - 登录框架

python - 拆分字符串,看起来像对参数的 Python 函数调用

python - 如何停止Python中的套接字线程?

python - 如何使用win32com从word文档中按颜色获取文本?

python - pyparsing 之后的下一步是什么?

python - 使用 Python 和 pyparsing 解析 Visual Basic 函数的参数列表

python - python 中的整数自增

python - Pyparsing Forward() 语法递归

python - pyparsing - 用千位分隔符解析数字

python - pyparsing - 解析日期