正则表达式选择最后一次出现和最后一次出现之间的所有内容

时间:2014-07-17 16:35:59

标签: regex

$string = "some text; other text; more other text; last text"

如何选择 '更多其他文字'
在此示例中,有 3个分号,但某些字符串可能或多或少。但总是至少2

我知道;(?!.*;)会找到最后一次出现。

3 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式:

;([^;]*);[^;]*$

并抓住匹配的组#1。

答案 1 :(得分:1)

使用lookbehind。这将匹配最后一个分号之前的文本

(?<=;)[^;]*(?=;[^;]*$)

DEMO

答案 2 :(得分:1)

如果您使用的是C#,最好使用

$string.Split(';')[2];

但是,如果总有4个部分的文本,那只能正常工作。如果有不同数量的部分,您仍然可以使用

int count = $string.Split(';').Count();

要查找部分的数量,请调用

$string.Split(';')[count - 1];

获取适当的元素。 我希望这是有道理的

对于PHP,当每次有4个元素时,它看起来像这样。

$string = "some text; other text; more other text; last text"
$pieces = explode(";", $string);
echo $pieces[2];

当有不同数量的分号时:

$string = "some text; other text; more other text; last text"
$pieces = explode(";", $string);
$count = count($pieces);
echo $pieces[$count - 1];
相关问题