Alon
Alon

Reputation: 7758

How to combine 2 conditions and more in regex

I want to create a regex that match '.', '#' and ':' and also match everything inside these brackets '[' & ']' such as [foo] & [bar]

I already have this match string.match(/[.#:]/g) for '.','#' and ':'.

I know that the brackets regex should look like this \[.\]

but how do I combine them both to one condition?

thanks, Alon

Upvotes: 0

Views: 14052

Answers (3)

kingpin
kingpin

Reputation: 1498

to combine them use

/[.#:]|(?:\[.+?\])/g

?: is optional and is used to not capture the group (anything in parenthesis)

UPDATE:

.+? (one or more) or .*?(for zero or more)- use this for lazy matching, otherwise [ sdfsdf][sdfsddf ] will be matched

Upvotes: 5

Scott Weaver
Scott Weaver

Reputation: 7361

var data = '[content]kjalksdjfa.sdf[sc.tt].#:';
var myregexp = /(\[.+?\])|[.#:]/g;
var match = myregexp.exec(data);
var result = "Matches:\n";
while (match != null) {
    result +=  "match:"+match[0] + ',\n';
    match = myregexp.exec(data);
}
alert(result);

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272106

var s = "a . b # c : d [foo]";
var m = /[.:#]|\[.*?\]/g;
s.match(m);
// returns [".", "#", ":", "[foo]"]

Upvotes: 2

Related Questions