本文介绍了正则表达式,“除字符串结尾之外”,问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 您好, 我的字符串如下: string =" WHITE / CLARET / PINK / XL" 我需要更改为这种格式: string =" WHITE-CLARET-PINK / XL" 我开发了以下功能。但是,有些东西是错的 我的正则表达式。它目前符合以下条件: / CLARET / PINK / XL 我想也许我可以用这样的东西排除包含 字符串结尾的匹配: r"([/] \\ \\ w + [^ $])" 但这也没有用。谁能告诉我如何排除最后的 比赛?字符串结尾的那个/ XL。 万分感谢, Derek Basch ------------------------------------------------ 导入重新 string =" WHITE / CLARET / PINK / XL" def replace_fs(thematch ): thematch = thematch.group(1) thematch =" - " + thematch [1:] 返回匹配 bs_regex = re.compile(r"([/] \ w +)")。sub( replace_fs,str(string)) print bs_regex 解决方案 你真的需要regexps吗? ''WHITE-CLARET-PINK / XL'' - David Eppstein http://www.ics.uci.edu / ~eppstein / 大学加州,欧文,信息学院和计算机科学 正如他们所说,如果你有问题并且想一个正则表达式 是解决它的最好方法,你现在可能有两个问题... 你总是想要排除最后一个/ ?怎么样呢 代替: s =''white / claret / pink / xl'' s2 = s.split(''/'')#临时列表 #加入所有但连续使用连字符,斜杠后添加最后 s ='' - ''.join(s2 [: - 1])+''/''+ s2 [-1] #s现在是''white-claret-pink / xl' ' 取决于格式是什么(例如/ XL 实际上是可选的吗?)它可能比 $更简单或更难b $ b这个。 可能也可以使用,但也许它可能不会很清楚。不会很清楚。 > -Peter Hello,I have a string like:string = "WHITE/CLARET/PINK/XL"which I need to alter to this format:string = "WHITE-CLARET-PINK/XL"I developed the below functions to do so. However, something is wrongwith my regular expression. It currently matches with the following:/CLARET/PINK/XLI thought perhaps I could exclude the match that includes the end of thestring with someting like this:r"([/]\w+[^$])"but that didnt work either. Can anyone tell me how to exclude the lastmatch? The one with the end of the string "/XL".Thanks a million,Derek Basch------------------------------------------------import restring = "WHITE/CLARET/PINK/XL"def replace_fs(thematch):thematch = thematch.group(1)thematch = "-" + thematch[1:]return thematchbs_regex = re.compile(r"([/]\w+)").sub(replace_fs, str(string))print bs_regex 解决方案Do you really need regexps for this?''WHITE-CLARET-PINK/XL''--David Eppstein http://www.ics.uci.edu/~eppstein/Univ. of California, Irvine, School of Information & Computer ScienceAs they say, if you have a problem and think a regular expressionis the best way to solve it, you might now have two problems...Do you always want to exclude the last "/" ? How about thisinstead:s = ''white/claret/pink/xl''s2 = s.split(''/'') # temporary list# join all but last with hyphens, add last after slashs = ''-''.join(s2[:-1]) + ''/'' + s2[-1]# s is now ''white-claret-pink/xl''Depending on what the format really is (e.g. is the /XLactually optional?) it might be simpler or harder thanthis.An re can be made to work too, probably, but perhaps itwon''t be very clear.-Peter 这篇关于正则表达式,“除字符串结尾之外”,问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 阿里云证书,YYDS! 05-24 00:16