![](/img/trans.png)
[英]Python - Splitting numbers and letters into sub-strings with regular expression
[英]python regular expression splitting some strings only in certain orders
我有以下tokenizeAndParse(s)函數,該函數接受一個字符串並嘗試將其令牌化為字符串數組
def tokenizeAndParse(s):
tokens = re.split(r"(\s+|assign|:=|print|\+|if|while|{|}|;|[|]|,|@|for|true|false|call|procedure|not|and|or|\(|\))", s)
tokens = [t for t in tokens if not t.isspace() and not t == ""]
print("hello",tokens)
函數的一些例子
tokenizeAndParse("assign abc := [true, true, true];")
hello ['assign', 'abc', ':=', '[', 'true', ',', 'true', ',', 'true', ']', ';']
tokenizeAndParse("print 5+5;")
hello ['print', '5', '+', '5', ';']
我遇到了一個有趣的問題,如果我調用以下命令,則不會將4和]解析為單獨的標記,我也不知道為什么。 如上所述,如果在[ ]之前為真 ,則該函數運行正常。
tokenizeAndParse("assign abc := [true, true, 4];")
hello ['assign', 'abc', ':=', '[', 'true', ',', 'true', ',', '4]', ';']
進一步使用該函數將表明,如果其在[ ]之前的數字,將無法正確解析。 這里發生了什么?
原因是您沒有拆分數字。 替換下面的代碼行:
tokens = re.split(r"(\s+|assign|:=|print|\+|if|while|{|}|;|[|]|,|@|for|true|false|call|procedure|not|and|or|\(|\))", s)
如下行所示:
>>> def tokenizeAndParse(s):
tokens = re.split(r"(\s+|assign|:=|print|\+|if|while|{|}|;|[|]|,|@|for|true|false|call|procedure|not|and|or|\(|\)|[0-9]+)", s)
tokens = [t for t in tokens if not t.isspace() and not t == ""]
print("hello",tokens)
>>> tokenizeAndParse("assign abc := [true, true, 4];")
('hello', ['assign', 'abc', ':=', '[', 'true', ',', 'true', ',', '4', ']', ';'])
這樣可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.