我正在使用第三方库,该库将字符串与双冒号::
连接在一起。我需要拆分该字符串,因为右侧的元素对我很重要,但左侧并不重要。
即
This is not what I want::what-i-want
请注意:右侧文本不包含任何:
个字符
我需要写一个正则表达式以使文本在右侧。
string.split(/::(.*)$/)
但这不起作用,因为左侧的文本确实可以包含:
个字符
正则表达式需要在这种情况下工作
var string = ":this:should:split::correctly:::and-return-this"
答案 0 :(得分:1)
答案 1 :(得分:0)
您可以使用正则表达式或字符串函数执行此操作:
正则表达式:
::
出现在 第一之后的文本-使用::(.+)
-即使字符串以{{ 1}} ::
之后的文本-使用::
-适用于带有^.*::(.*)
的字符串在最后一个:
之后,但是如果最后一个字符为::
::
字符串函数:
您可以使用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)
您可以分割一个双冒号,并断言左右的字符是除冒号以外的任何字符。
(?<=[^:])::(?=[^:])
let s = ":this:should:split::correctly:::and-return-this";
console.log(s.split(/(?<=[^:])::(?=[^:])/).pop());
如果您还想在::
位于字符串的开头或结尾时进行拆分:
(?<!:)::(?!:)