匹配字符串中的确切单词

问题描述 投票:1回答:3

我需要一种方法来匹配一个字符串而不是误报。让我举一个我的意思的例子:

  • “/ thing”应匹配字符串“/ a / thing”
  • “/ thing”应匹配字符串“/ a / thing / that / is / here”
  • “/ thing”不应与字符串“/ a / thing_foo”匹配

基本上,如果第一个字符串和第二个字符串中存在确切的字符,它应该匹配,但如果第二个字符串中存在run-ons则不匹配(例如thing_foo中的下划线)。

现在,我正在这样做,这是行不通的。

let found = b.includes(a); // true

希望我的问题很清楚。谢谢您的帮助!

javascript delimited-text
3个回答
2
投票

男孩这样做了经典的XY Problem

如果我不得不猜测,你想知道路径是否包含特定的段。

在这种情况下,将positive lookahead上的字符串拆分为'/'并使用Array.prototype.includes()

const paths = ["/a/thing", "/a/thing/that/is/here", "/a/thing_foo"]
const search = '/thing'

paths.forEach(path => {
  const segments = path.split(/(?=\/)/)
  console.log('segments', segments)
  console.info(path, ':', segments.includes(search))
})

使用正向前瞻性表达式/(?=\/)/允许我们在/上拆分字符串,同时在每个段中保持/前缀。


或者,如果您仍然非常热衷于使用直接正则表达式解决方案,那么您将需要这样的东西

const paths = ["/a/thing", "/a/thing/that/is/here", "/a/thing_foo", "/a/thing-that/is/here"]
const search = '/thing'

const rx = new RegExp(search + '\\b') // note the escaped backslash

paths.forEach(path => {
  console.info(path, ':', rx.test(path))
})

请注意,如果搜索字符串后跟连字符或波形符号,则会返回误报,因为它们被视为字边界。你需要一个更复杂的模式,我认为第一个解决方案可以更好地处理这些情况。


1
投票

我建议使用正则表达式......

例如以下正则表达式/\/thing$/ - 匹配以/thing结尾的任何内容。

console.log(/\/thing$/.test('/a/thing')) // true
console.log(/\/thing$/.test('/a/thing_foo')) // false

更新:使用变量...

var search = '/thing'
console.log(new RegExp(search + '$').test('/a/thing')) // true
console.log(new RegExp(search + '$').test('/a/thing_foo')) // false

0
投票

只需使用以下正则表达式即可

var a = "/a/thing";
var b = "/a/thing/that/is/here";
var c = "/a/thing_foo";
var pattern = new RegExp(/(:?(thing)(([^_])|$))/);
pattern.test(a) // true
pattern.test(b) // true
pattern.test(c)  // false
© www.soinside.com 2019 - 2024. All rights reserved.