Richard
Richard

Reputation: 65510

Regular expressions in JavaScript: match multiple substrings at the beginning of a string?

I want to build a JavaScript regular expression to match all words starting with "ad" or "ae", or all words that contain "-ad" and "-ae".

This is what I've tried:

var regex_string = "^[ad|ae]|-[ad|ae]";
var re = RegExp(regex_string, "i");

var matches = _.filter(data, function(r) {
  if (re.test(r)) {
    return true;
  }
});

However, this is matching all words beginning with 'a', 'd' or 'e'.

How can I amend the regex to match only those strings?

JSFiddle here: http://jsfiddle.net/xGgan/1/

Upvotes: 2

Views: 290

Answers (3)

user1636522
user1636522

Reputation:

Here my interpretation of "-ae AND -ad" :

/^(?:ad|ae)|-ad.*-ae|-ae.*-ad/

Upvotes: 0

Jerry
Jerry

Reputation: 71538

[ ... ] denotes a character class and anything inside will match regardless of position. Additionally, [ae] matches only one character, either a or e.

For what your doing, translating it directly would give:

(?:^(?:ad|ae)|-(?:ad|ae))

You use | in groups ( ( ... ) for capture groups and (?: ... ) for non-capture groups; the latter are preferable if you don't intend to save captures for later use, as they improve the regex speed wise and memory wise).

But that can be optimised a bit:

(?:^|-)a[ed]

should match just as fine.

Upvotes: 3

epascarello
epascarello

Reputation: 207501

Because [] is match any letter inside So it says "match a or d or | or a or e". You need to use a capture group instead with the or.

Try

var regex_string = "(^(ad|ae)|-(ad|ae))";

Upvotes: 3

Related Questions