How to make the prefix and captured characters optional in Regex? -


given following string,

var str = "<%= stylesheet_link_tag 'project/theme-one', media: 'all' if @auth.show?  %>" 

below regex returns valid match,

str.match(/\<%= stylesheet_link_tag\s+['"]?(.*)['"],.+if(.*)%\>/)  // [ //  "<%= stylesheet_link_tag 'project/theme-one', media: 'all' if @auth.show?  %>",  //  "project/theme-one",  //  " @auth.show?  " // ] 

however, fails following string (without if-condition):

var str = "<%= stylesheet_link_tag 'project/theme-one', media: 'all' %>"  // expected result // [ //  "<%= stylesheet_link_tag 'project/theme-one', media: 'all' if @auth.show?  %>",  //  "project/theme-one",  //  " " // ] 

how makeif(.*) part of regex optional?

in general, make pattern optional (i.e. matching 1 or 0 times) need use ? quantifier. if have single symbol, ? can appended after it. if have sequence of subpatterns, best way place them non-capturing group (?:...) , add ? after it.

you can use

<%= stylesheet_link_tag\s+['"]?(.*?)['"],.+?(?:if(.*))?%>                                   ^        ^^^^^^^^^^^^   

see regex demo

an important point here first .+ greedy, , ate optional (?:if(.*))? part. .+ should turned lazy +?. also, optimize pattern bit, need use lazy dot matching in between ['"]? , ['"].

js demo:

var re = /<%= stylesheet_link_tag\s+['"]?(.*?)['"],.+?(?:if(.*))?%>/g;   var str = '<%= stylesheet_link_tag \'project/theme-one\', media: \'all\' if @auth.show?  %>\n<%= stylesheet_link_tag \'project/theme-one\', media: \'all\' %>';    var res0 = [];   var res1 = [];   var res2 = [];     while ((m = re.exec(str)) !== null) {   res0.push(m[0]);   res1.push(m[1]);   res2.push(m[2]);  }  console.log(res0);  console.log(res1);  console.log(res2);


Comments