简体   繁体   English

使用正则表达式按字符拆分

[英]Splitting by character using regular expressions

I want to split a string by the char '-' along with the spaces to the left and right of it. 我想用char '-'分隔一个字符串以及它左边和右边的空格。 How can I do this? 我怎样才能做到这一点?

I tried a few things: 我试了几件事:

a.split('[\s]-[\s]')
a.split( *- *)
a.split(\s-\s)

If you want to remove all spaces around the '-', use this regex. 如果要删除“ - ”周围的所有空格,请使用此正则表达式。

\s*-\s*

If you only want one optional space on either side, use this one. 如果您只想在任一侧使用一个可选空间,请使用此空间。

\s?-\s?
import re
s = 'abc-abc- abc -abc - abc'
r = re.compile('\s*-\s*')
r.split(s)

Will give 会给

['abc', 'abc', 'abc', 'abc', 'abc']
s='one - two - three - four'

print re.split(r'\s*-\s*',s)

prints: 打印:

['one', 'two', 'three', 'four']

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

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