正则表达式以获取最后出现的“ ::”字符

时间:2020-09-16 02:37:49

标签: javascript regex regex-lookarounds regex-group

我正在使用第三方库,该库将字符串与双冒号::连接在一起。我需要拆分该字符串,因为右侧的元素对我很重要,但左侧并不重要。

This is not what I want::what-i-want

请注意:右侧文本不包含任何:个字符

我需要写一个正则表达式以使文本在右侧。

string.split(/::(.*)$/)

但这不起作用,因为左侧的文本确实可以包含:个字符

正则表达式需要在这种情况下工作

var string = ":this:should:split::correctly:::and-return-this"

3 个答案:

答案 0 :(得分:1)

尝试此正则表达式:

/::([^:]*)$/

regex101.com上测试

答案 1 :(得分:0)

您可以使用正则表达式或字符串函数执行此操作:

正则表达式:

  • 要获取:: 出现在 第一之后的文本-使用::(.+)-即使字符串以{{ 1}}
  • 要获取在{strong> 最后出现的:: 之后的文本-使用::-适用于带有^.*::(.*)的字符串在最后一个:之后,但是如果最后一个字符为::
  • ,则不会返回任何内容

::

字符串函数:

您可以使用var string = ":this:should:split::correctly:::and-return-this"; var result = /::(.+)/.exec(string)[1]; console.log("After first occurrence = " + result); var string = ":this:should:split::correctly:::and-return-this"; var result = /^.*::(.*)/.exec(string)[1]; console.log("After last occurrence = " + result); var string = ":this:should:split::correctly:::and-return:this"; var result = /^.*::(.*)/.exec(string)[1]; console.log("Single : in last part = " + result); var string = ":this:should:split::correctly:::and-return-this:"; var result = /^.*::(.*)/.exec(string)[1]; console.log("Ends with : = " + result); var string = ":this:should:split::correctly:::and-return-this::"; var result = /^.*::(.*)/.exec(string)[1]; console.log("Ends with :: = " + result); var string = "::this:should:split::correctly:::and-return-this"; var result = /^.*::(.*)/.exec(string)[1]; console.log("Starts with :: = " + result); / indexOf来获取lastIndexOf的位置,然后::从该位置到结尾的字符串。

indexOf documentation
lastIndexOf Dcoumentation
Slice Documentation

slice

答案 2 :(得分:0)

您可以分割一个双冒号,并断言左右的字符是除冒号以外的任何字符。

(?<=[^:])::(?=[^:])

Regex demo

let s = ":this:should:split::correctly:::and-return-this";
console.log(s.split(/(?<=[^:])::(?=[^:])/).pop());

如果您还想在::位于字符串的开头或结尾时进行拆分:

(?<!:)::(?!:)

Regex demo