如何在不同的分隔符上拆分字符串,但保留输出中的某些分隔符?(标记一个字符串) [英] How do I split a string on different delimiters, but keeping on the output some of said delimiters? (Tokenize a string)
问题描述
更具体地说,我想在任何非字母数字字符上拆分字符串,但在分隔符不是空格的情况下,我想保留它.即对输入:
More specifically I want to split a string on any non alpha-numeric character but in the case that the delimiter is not a white space I want to keept it. That is, to the input:
my_string = 'Hey, I\'m 9/11 7-11'
我想得到:
['Hey' , ',' , 'I' , "'" , 'm', '9' , '/' , '11', '7' , '-' , '11']
没有空格作为列表元素.
Without no whitespace as a list element.
我尝试了以下方法:
re.split('([/\'\-_,.;])|\s', my_string)
但是输出:
['Hey', ',', '', None, 'I', "'", 'm', None, '9', '/', '11', None, '7', '-', '11']
如何在没有不必要"迭代的情况下解决这个问题?
How do I solve this without 'unnecessary' iterations?
我在转义反斜杠字符时也遇到了一些麻烦,因为 '\\\\'
似乎不起作用,关于如何解决这个问题的任何想法?
Also I have some trouble with escaping the backslash character, since '\\\\'
does not seem to be working, any ideas on how to also solve this?
非常感谢.
推荐答案
您可以使用
import re
my_string = "Hey, I'm 9/11 7-11"
print(re.findall(r'\w+|[^\w\s]', my_string))
# => ['Hey', ',', 'I', "'", 'm', '9', '/', '11', '7', '-', '11']
查看 Python 演示
\w+|[^\w\s]
正则表达式匹配 1+ 个单词字符(字母、数字、_
符号)或除 a 之外的单个字符单词和空格字符.
The \w+|[^\w\s]
regex matches either 1+ word chars (letters, digits, _
symbols) or a single character other than a word and whitespace char.
顺便说一句,要将反斜杠与正则表达式匹配,您需要在原始字符串文字 (r'\\'
) 中使用 \\
或在 a 中使用 4 个反斜杠常规的 ('\\\\'
).建议使用原始字符串文字在 Python 中定义正则表达式模式.
BTW, to match a backslash with a regex, you need to use \\
in a raw string literal (r'\\'
) or 4 backslashes in a regular one ('\\\\'
). It is recommended to use raw string literals to define a regex pattern in Python.
这篇关于如何在不同的分隔符上拆分字符串,但保留输出中的某些分隔符?(标记一个字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!