簡體   English   中英

用於簡單表達的Python正則表達式標記生成器

[英]Python regex tokenizer for simple expression

我寫了這個正則表達式,將表達式'res = 3 + x_sum * 11'拆分為lexemes

import re
print(re.findall('(\w+)(=)(\d+)(\*|\+)(\w+)(\*|\+)(\d+)', 'res=3+x_sum*11'))

我的輸出看起來像這樣:

[('res', '=', '3', '+', 'x_sum', '*', '11')]

但我希望re.findall返回一個lexemes及其標記的列表,以便每個lexeme都在它自己的組中。 該輸出應如下所示:

[('', 'res', ''), ('', '', '='), ('3', '', ''), ('', '', '+'),

('', 'x_sum', ''), ('', '', '*'), ('11', '', '')] 

如何讓re.findall返回這樣的輸出

您可以使用標記字符串

re.findall(r'(\d+)|([^\W\d]+)|(\W)', s)

請參閱正則表達式演示 請注意,一旦模式包含多個捕獲組, re.findall返回元組列表。 上面的模式包含3個捕獲組,因此,每個元組包含3個元素:1 +數字,1 +字母/下划線或非字char。

更多細節

  • (\\d+) - 捕獲組1:1+位數
  • | - 要么
  • ([^\\W\\d]+) - 捕獲組2:非字和數字字符(字母或下划線)以外的1 +字符
  • | - 要么
  • (\\W) - 捕獲第3組:非單詞char。

參見Python演示

import re
rx = r"(\d+)|([^\W\d]+)|(\W)"
s = "res=3+x_sum*11"
print(re.findall(rx, s))
# => [('', 'res', ''), ('', '', '='), ('3', '', ''), ('', '', '+'), ('', 'x_sum', ''), ('', '', '*'), ('11', '', '')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM