简体   繁体   中英

Matching an exact word from a string

I need a way to match a word against a string and not get false positives. Let me give an example of what I mean:

  • "/thing" should match the string "/a/thing"
  • "/thing" should match the string "/a/thing/that/is/here"
  • "/thing" should NOT match the string "/a/thing_foo"

Basically, it should match if the exact characters are there in the first string and the second, but not if there are run-ons in the second (such as an underscore like in thing_foo ).

Right now, I'm doing this, which is not working.

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

Hopefully my question is clear enough. Thanks for the help!

Boy did this turn in to a classic XY Problem .

If I had to guess, you want to know if a path contains a particular segment.

In that case, split the string on a positive lookahead for '/' and use 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)) }) 

Using the positive lookahead expression /(?=\\/)/ allows us to split the string on / whilst maintaining the / prefix in each segment.


Alternatively, if you're still super keen in using a straight regex solution, you'll want something like this

 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)) }) 

Note that this will return false positives if the search string is followed by a hyphen or tilde as those are considered to be word boundaries. You would need a more complex pattern and I think the first solution handles these cases better.

I'd recommend using regular expressions...

eg The following regular expression /\\/thing$/ - matches anything that ends with /thing .

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

Update: To use a variable...

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

Simply with following regex you can do it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM