How to combine 2 conditions and more in regex

2019-06-09 11:05发布

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

3条回答
一夜七次
2楼-- · 2019-06-09 11:31
var s = "a . b # c : d [foo]";
var m = /[.:#]|\[.*?\]/g;
s.match(m);
// returns [".", "#", ":", "[foo]"]
查看更多
Summer. ? 凉城
3楼-- · 2019-06-09 11:46
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);
查看更多
做个烂人
4楼-- · 2019-06-09 11:54

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

查看更多
登录 后发表回答