Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Js regex allow optional line break and space indentation

Some relative posts:


let s = `
%nav.cf
  %ul.cf
    %li
      %a{
        :href => "#"
      } Item 1
    %li
      %a{href => "#"} Item 2
    %li
      %a{:href => "#"} Item 2
    %li
      %a{:href => "#"} Item 3

  %a{:href => "#", :id => "openup"} MENU

%h1 Basic Responsive Menu
%p Playing around and learning HAML + SCSS - Basic Responsive Menu.
`;

s.replace(/\{?[\r\n]+.*\=\>(.*)\}/g, cd=>{
  console.log(cd);
});

/*
      %a{href => "#"}

      %a{:href => "#"}

      %a{:href => "#"}


  %a{:href => "#", :id => "openup"}
*/

s.replace(/\{?[\r\n]+.*\=\>(.*)[\s]+\}/g, cd=>{
  console.log(cd);
});
/*
{
        :href => "#"
      }
*/

I am writing an adopter for a template engine, basically I need to extract all the hash insides {} that must have a =>.

The expected result are all the commented values above. which the code either returns first or the second.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
        :href => "#"
      }
%a{href => "#"}
%a{:href => "#"}
%a{:href => "#"}
 %a{:href => "#", :id => "openup"}

please have a look at the second expression, where I try to allow the optional line break and spaces indentation, I wonder why it gets rid of the unescaped hashes returned before.

>Solution :

You don’t need to use replace. Just use this regex for matching in MULTILINE mode

^[^{}\n]*{(?=[^}]*#)[^}]*=>[^}]*}

RegEx Demo

Code:

let s = `
%nav.cf
  %ul.cf
    %li
      %a{
        :href => "#"
      } Item 1
    %li
      %a{href => "#"} Item 2
    %li
      %a{:href => "#"} Item 2
    %li
      %a{:href => "#"} Item 3

  %a{:href => "#", :id => "openup"} MENU

%h1 Basic Responsive Menu
%p Playing around and learning HAML + SCSS - Basic Responsive Menu.`;

console.log( s.match(/^[^{}\n]*{(?=[^}]*#)[^}]*=>[^}]*}/gm) );

RegEx Details:

  • ^: Start
  • [^{}\n]*: Match 0 or more of any characters that are not { and } and a line break
  • {: Match a {
  • (?=[^}]*#): Lookahead to make sure that we have a # before matching }
  • [^}]*: Match 0 or more of any characters that are not }
  • =>: Match a =>
  • [^}]*: Match 0 or more of any characters that are not }
  • }: Match a }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading