1

我正在尝试通过使用 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>"));

我查看了文档,但找不到与“ LeadBy”等效FollowedBy的方法或实现该方法的方法。

4

1 回答 1

2

您要求的是“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)
于 2012-08-02T12:41:19.403 回答