我有以下字符串:
"string.isnotimportant"
我想找到点(它可以是任何非字母数字字符),并将其移到字符串的末尾。
结果应如下所示:
"stringisnotimportant."
我正在寻找一个正则表达式来完成这项工作。
>>> import re
>>> string = "string.isnotimportant"
#I explain a bit about this at the end
>>> regex = '\w*(\W+)\w*' # the brackets in the regex mean that item, if matched will be stored as a group
#in order to understand the re module properly, I think your best bet is to read some docs, I will link you at the end of the post
>>> x = re.search(regex, string)
>>> x.groups() #remember the stored group above? well this accesses that group.
#if there were more than one group above, there would be more items in the tuple
('.',)
#here I reassign the variable string to a modified version where the '.' is replaced with ''(nothing).
>>> string = string.replace('.', '')
>>> string += x.groups()[0] # here I basically append a letter to the end of string
该+=
运营商追加一个字符的字符串的结束。由于字符串不像列表那样具有.append方法,因此这是一个方便的功能。x.groups()[0]
指的是上面的元组的第一个项目(在这种情况下,仅此项目)。
>>> print string
"stringisnotimportant."
关于正则表达式:
“ \ w”匹配任何字母数字字符和下划线:a到z,A到Z,0到9和'_'。
“ \ W”匹配任何非字母数字字符。这样的示例包括“&”,“ $”,“ @”等。
https://developers.google.com/edu/python/regular-expressions?csw=1
http://python.about.com/od/regularexpressions/a/regexprimer.htm
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句