我是regex库的新手,我正试图从类似的文本中生成
"""constructor SquareGame new(){
let square=square;
}"""
这会输出一个列表:
['constructor', 'SquareGame', 'new', '(', ')', '{', 'n', 'let', 'square', '=', 'square', ';', '}']
我需要创建一个由空格、新行和这个符号{}()[].;,+-*/&|<>=~
分隔的令牌列表。
我使用了re.findall('[,;.()={}]+|S+|n', text)
,但似乎只使用空格和新行来分隔标记。
您可以使用
re.findall(r'w+|[^w t]', text)
为了避免匹配任何Unicode水平空白,请使用
re.findall(r'w+|[^w tu00A0u1680u2000-u200Au202Fu205Fu3000]', text)
请参阅regex演示详细信息:
w+
-1个或多个单词字符|
-或[^w t]
-不是空格和制表符的单个非单词字符(因此,所有垂直空格都匹配)
您可以在[^w t]
字符类中添加更多要排除的水平空白字符,请在匹配空白但不匹配换行符处查看它们的列表。正则表达式将类似于w+|[^w tu00A0u1680u2000-u200Au202Fu205Fu3000]
。
请参阅Python演示:
import re
pattern = r"w+|[^w t]"
text = "constructor SquareGame new(){nlet square=square;n}"
print ( re.findall(pattern, text) )
# => ['constructor', 'SquareGame', 'new', '(', ')', '{', 'n', 'let', 'square', '=', 'square', ';', 'n', '}']
此正则表达式将仅根据您指示的字符进行匹配,我认为这是一种更安全的方法。
>>> re.findall(r"w+|[{}()[].;,+-*/&|<>=~n]", text)
['constructor', 'SquareGame', 'new', '(', ')', '{', 'n', 'let', 'square', '=', 'square', ';', 'n', '}'