尤慕李 尤慕李 - 2 months ago 9
Javascript Question

find all words that contains `p` but not `ph`

Say,

str = 'python php ruby javascript jsonp perhapsphpisoutdated'


How do you find all words that contains
p
but not
ph
using regex?

I know how to solve it with
split
&
filter
:

str.split(' ')
.filter( w=>w.includes('p') && !w.includes('ph') )


Is there a possible regex way?

Answer

You may use the following solution:

var str = 'python php ruby javascript jsonp perhapsphpisoutdated';
var res = str.match(/\b(?!\w*ph)\w*p\w*/g);
console.log(res);

Description:

  • \b - leading word boundary
  • (?!\w*ph) - a negative lookahead requiring that there cannot be ph after 0+ word chars that appear right after the leading word boundary
  • \w* - 0+ word chars
  • p - a letter p
  • \w* - 0+ word chars.

Note that \w matching letters, digits and underscores can be replaced with [a-zA-Z] to only match ASCII letters.

Visualization:

https://jex.im/regulex/#!embed=false&flags=&re=%5Cb(%3F!%5Cw*ph)%5Cw*p%5Cw*

Comments