正则表达式查找包含至少一个星号的所有单词

问题描述 投票:0回答:2

正则表达式模式,匹配该单词中任何位置包含至少一个星号的所有单词。

str = "t*e *pp locall* so my q**st*on is **stinct *ro* t*eir's. *ev***heles* lol ****"

应该匹配

t*e *pp locall*所以我的q**st*on**stinct *ro* t*eir's*ev***heles* lol ****

javascript regex
2个回答
4
投票
[\w-']*(?:\*+[\w-']*)+
  • [\w-']*任何单词匹配任何单词character,-'
  • (?:\*+[\w-']*)+匹配以下一次或多次 \*+匹配*一次或多次 [\w-']*任何单词匹配任何单词character,-'

let s = `t*e *pp locall* so my q**st*on is **stinct *ro* t*eir's. *ev***heles* lol ****`
let r = /[\w-']*(?:\*+[\w-']*)+/g

while(m = r.exec(s)) {
  console.log(m[0])
}

1
投票

也许你在寻找这个?

/[^\s\.,?!]*\*+[^\s\.,?!]*/g
  • [^\s\.,?!]*匹配任何字符零次或多次不是空格或标点符号。
  • \*+匹配*一次或多次。
  • [^\s\.,?!]*继续匹配字符,直到遇到空格或标点符号,并终止匹配。

我投入了更多标点符号,因为你似乎想要从匹配中省略它:

var str = "t*e *pp locall* so my q**st*on is **stinct *ro* t*eir's. *ev***heles* lol ****"
console.log(str.match(/[^\s\.,?!]*\*[^\s\.,?!]*/g))
© www.soinside.com 2019 - 2024. All rights reserved.