首页 > 解决方案 > 正则表达式获取字符串,直到在 javascript 中出现特殊字符

问题描述

我有一个如下所示的字符串

str = "I have candy='4' and ice cream = 'vanilla'"

我想将术语放在 latest 的左侧,=并且应该获取术语,直到另一个=.

所以我的字符串应该是

leftOfEqual = "'4' and ice cream"

另一个例子

str = "I have candy='4' and ice cream = 'vanilla' and house='big'"

leftOfEqual = "'vanilla' and house"

这是我regex目前

leftOfEqual = str.match(/\S+(?= *=)/)[0]

但它只看第一个=,只给我左边的直接单词。

我怎样才能做到这一点?

注意:=如果latest 左侧没有存在=,我应该得到完整的字符串直到开始。

标签: javascriptregexstring

解决方案


使用splitandslice查找倒数第二个拆分组。
lastIndexOf解决方案,只从后面搜索。先找到=,然后继续下一个=,在它们之间切分。

str = "I have candy='4' and ice cream = 'vanilla'"
console.log(
str.split('=').slice(-2)[0]
)

console.log(
str.slice(str.lastIndexOf('=',x=str.lastIndexOf('=')-1)+1,x<-1?undefined:x)
)

str = "and ice cream = 'vanilla'"
console.log(
str.split('=').slice(-2)[0]
)

console.log(
str.slice(str.lastIndexOf('=',x=str.lastIndexOf('=')-1)+1,x<-1?undefined:x)
)

str = "I have cand'4' and ice cream 'vanilla'"
console.log(
str.split('=').slice(-2)[0]
)

console.log(
str.slice(str.lastIndexOf('=',x=str.lastIndexOf('=')-1)+1,x<-1?undefined:x)
)


推荐阅读