2024-04-18 23:45:20 发布
网友
如果我有如下字符串:
foo_bar_one_two_three
对于RegEx,是否有一种干净的方法返回:foo_bar_one_two?
foo_bar_one_two
我知道我可以用split,pop和join来解决这个问题,但我正在寻找一个更干净的解决方案。
result = my_string.rsplit('_', 1)[0]
其行为如下:
>>> my_string = 'foo_bar_one_two_three' >>> print(my_string.rsplit('_', 1)[0]) foo_bar_one_two
请参见文档项中的^{}。
与rsplit解决方案类似,rpartition也可以工作:
rsplit
rpartition
result = my_string.rpartition("_")[0]
您需要注意没有找到分隔符的情况。在这种情况下,原始字符串将在索引2中,而不是0中。
文档字符串:
rpartition(...)S.rpartition(sep) -> (head, sep, tail)Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.
rpartition(...)
S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.
一种方法是使用rfind获取最后一个_字符的索引,然后对字符串进行切片以提取到该点的字符:
rfind
_
>>> s = "foo_bar_one_two_three" >>> idx = s.rfind("_") >>> if idx >= 0: ... s = s[:idx] ... >>> print s foo_bar_one_two
在使用它获取子字符串之前,需要检查rfind调用是否返回大于-1的值,否则它将去掉最后一个字符。
如果必须使用正则表达式(对于这样的简单情况,我倾向于使用非正则表达式解决方案),可以这样做:
>>> import re >>> s = "foo_bar_one_two_three" >>> re.sub('_[^_]*$','',s) 'foo_bar_one_two'
其行为如下:
请参见文档项中的^{} 。
与
rsplit
解决方案类似,rpartition
也可以工作:您需要注意没有找到分隔符的情况。在这种情况下,原始字符串将在索引2中,而不是0中。
文档字符串:
一种方法是使用
rfind
获取最后一个_
字符的索引,然后对字符串进行切片以提取到该点的字符:在使用它获取子字符串之前,需要检查
rfind
调用是否返回大于-1的值,否则它将去掉最后一个字符。如果必须使用正则表达式(对于这样的简单情况,我倾向于使用非正则表达式解决方案),可以这样做:
相关问题 更多 >
编程相关推荐