简体   繁体   English

用python中的新行、符号和带空格的正则表达式分割字符串

[英]Split string with regex by new lines, symbols and withspaces in python

I'm new to regex library, and I'm trying to make from a text like this我是 regex 库的新手,我正在尝试用这样的文本制作

"""constructor SquareGame new(){
let square=square;
}"""

This outputs a list:这会输出一个列表:

['constructor', 'SquareGame', 'new', '(', ')', '{', '\n', 'let', 'square', '=',  'square', ';', '}']

I need to create a list of tokens separated by white spaces, new lines and this symbols {}()[].;,+-*/&|<>=~ .我需要创建一个由空格、换行符和这个符号{}()[].;,+-*/&|<>=~分隔的标记列表。

I used re.findall('[,;.()={}]+|\\S+|\\n', text) but seems to separate tokens by withe spaces and new lines only.我使用了re.findall('[,;.()={}]+|\\S+|\\n', text)但似乎只用空格和新行分隔标记。

You may use您可以使用

re.findall(r'\w+|[^\w \t]', text)

To avoid matching any Unicode horizontal whitespace use为了避免匹配任何Unicode 水平空白使用

re.findall(r'\w+|[^\w \t\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]', text)

See the regex demo .请参阅正则表达式演示 Details :详情

  • \\w+ - 1 or more word chars \\w+ - 1 个或多个字字符
  • | - or - 要么
  • [^\\w \\t] - a single non-word char that is not a space and a tab char (so, all vertical whitespace is matched). [^\\w \\t] - 不是空格和制表符的单个非单词字符(因此,匹配所有垂直空格)。

You may add more horizontal whitespace chars to exclude into the [^\\w \\t] character class, see their list at Match whitespace but not newlines .您可以添加更多水平空白字符以排除在[^\\w \\t]字符类中,请参阅Match whitespace but not newlines 中的列表。 The regex will look like \\w+|[^\\w \\t\ \ \ -\ \ \ \ ] .正则表达式看起来像\\w+|[^\\w \\t\ \ \ -\ \ \ \ ]

See the Python demo :请参阅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', '}']

This regex will only match based on the characters that you indicated and I think this is a safer method.此正则表达式只会根据您指示的字符进行匹配,我认为这是一种更安全的方法。

>>> re.findall(r"\w+|[{}()\[\].;,+\-*/&|<>=~\n]", text)
['constructor', 'SquareGame', 'new', '(', ')', '{', '\n', 'let', 'square', '=', 'square', ';', '\n', '}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM