1

Ok, I want to combine two regular expressions. In the example below, I want to extract any word which has only the letters specified, then of that list, only words with another letter, r in this example.

I have read several articles on this forum.

One for example is: Combining regular expressions in Javascript

They say to combine the expressions with |, exp1|exp2. That's what I did, but I get words I shouldn't. How can I combine r1 and r2 in the example below?

Thanks for your help.

//the words in list form.
var a = "frog dog trig srig swig strog prog log smog snog fig pig pug".split(" "),
//doesn't work, can we fix?
     r = /^[gdofpr]+$|[r]+/,
    //These work.
    r1 = /^[gdofpr]+$/,
    r2 = /[r]+/,
    //save the matches in a list.
    badMatch = [], 
    goodMatch = [];
//loop through a.
for (var i = 0; i < a.length; i++) {
    //bad, doesn't get what I want.
    if (a[i].match(r)) badMatch[badMatch.length] = a[i];
    //works, clunky. Can we combine these?
    if (a[i].match(r1) && a[i].match(r2)) goodMatch[goodMatch.length] = a[i];
} //i
alert(JSON.stringify([badMatch, goodMatch])); //just to show what we got.

I get the following.

[
    ["frog", "dog", "trig", "srig", "strog", "prog"],
    ["frog", "prog"]]

Again, thanks.

Community
  • 1
  • 1
user1942362
  • 142
  • 2
  • 11
  • javascript != java – Justinas May 10 '16 at 09:25
  • 1
    Does it mean you need to get all words that only consist of the characters in `^[gdofpr]+$` and also contain `r`? `/^[gdofpr]*r[gdofpr]*$/`? – Wiktor Stribiżew May 10 '16 at 09:26
  • Combining with `|` will match either, not both. – nnnnnn May 10 '16 at 09:38
  • Is the question that you want to solve this particular query, or that you want to arbitrarily "AND" two regexes in a single expression? If the former then @Wiktor has given you a workable answer. – Brett May 10 '16 at 09:47
  • I do not think it is feasible to provide a generic solution for ANDing regexps. There are different scenrios: 1) lookahead AND (e.g. `^(?!p1$)p2$`), 2) dot matching AND (e.g. `p1.*p2|p2.*p1`), 3) building a totally new regex using the conditions deduced from `p1` and `p2` - and maybe more. – Wiktor Stribiżew May 10 '16 at 09:51
  • Thank you all. I am writing a web app to teach typing. I want to take all the letters the user has mastered, add the new letter the user is working on, then pick all the words that have this letter so s/he can practice. The answer was perfect. I am new to regex creation. When I saw that answer, the light bulb went on. Thanks all, good work! – user1942362 May 10 '16 at 10:09

1 Answers1

3

To only match string consisting of g, d, o, f, p and r characters and that also have r, use

/^[gdofpr]*r[gdofpr]*$/

See the regex and JS demo:

var a = "frog dog trig srig swig strog prog log smog snog fig pig pug".split(" ");
var res = a.filter(x => /^[gdofpr]*r[gdofpr]*$/.test(x));
document.body.innerHTML = JSON.stringify(res, 0, 4);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563