1
我試圖通過使用PyParsing刪除前導或尾隨空白字符來清除一些代碼。去除前導空白是很容易的,因爲我可以使用FollowedBy
子類匹配字符串,但不包含它。現在我需要跟隨我的標識字符串的東西。如何在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但找不到相當於「LeadBy
」到FollowedBy
或者如何實現這一點。
感謝保羅!那正是我所期待的。由於更復雜的問題,我會堅持第一個解決方案(雖然我真的很喜歡第二個實現,並試圖記住那個)。 – 2012-08-02 15:06:36