简体   繁体   中英

regex to match 2 different words in a string

I've went through so many posts about this but can't find one that works. I have object keys that I want to search through and see if they have either of two specific words in them and filter them if the exist.

Example:

const obj = {
   time_pop: 'fhfvla',
   icon: 'dsfval',
   home_pops: 'valffg',
   title: 'sdfsdfs',
   pop: 'sfsdfsd',
   rattle: 'sdfdsf',
   pops: 'sfsdfsdf'
}

I want a regex that can find either the word pop || pops in object keys. I'm currently looping through and have the key and am using this as my regex

  const expr = /\b(pop|pops)\b/;

  const only = Object.entries(obj).filter(([k, v]) => {
    return expr.test(k);
  })

The above only works for one word not if it has a _ in it. For example this is not working. time_pop home_pops

They are return false when they should return true because the word pop or pops is in them.

You can use /pops?/ if you want to match partially.

 const obj = {time_pop: 'fhfvla',icon: 'dsfval',home_pops: 'valffg',title: 'sdfsdfs',pop: 'sfsdfsd',rattle: 'sdfdsf',pops: 'sfsdfsdf'} const only = Object.entries(obj).filter(([k, v]) => { return /pops?/g.test(k) }) console.log(only) 

Here, there were also errors (syntax) in your code.

 const obj = { time_pop: 'fhfvla', icon: 'dsfval', home_pops: 'valffg', title: 'sdfsdfs', pop: 'sfsdfsd', rattle: 'sdfdsf', pops: 'sfsdfsdf' }; const expr = /pop|pops/; const only = Object.entries(obj).filter(([k, v]) => expr.test(k)); console.log(only); 

In a regular expression, the metacharacter \\b represents a word boundary. Essentially, it will only match if there is a non-word character before (pop|pops) . An underscore, however, is a word character. Try:

const expr = /(\b|_)(pop|pops)\b/

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