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

Regex – extract string between double quotes where line starts with a keyword

Given the following lines:

classes!("text-xl", "text-blue-500")
String::from("test")
classes!("text-sm")

I wish to extract text-xl, text-blue-500 and text-sm and potentially any other strings within classes!

What I have so far is:

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

  • (?<=classes!).* – this gives me everything after classes! but not
    the exact values
  • (?!^")".*?" – this gives me the values I want with but with the quotes
  • I use the global and multi line flags

>Solution :

If you are using Javascript, and the positive lookbehind is supported (you don’t need the multiline flag, only the global flag)

(?<=classes!\((?:"[^"]*",\s*)*")[^"]*(?=")
  • (?<= Positive lookbehind to assert to the left
    • classes!\( Match classes!(
    • (?:"[^"]*",\s*)* Match optional repetitions of "...",
    • " Match a double quote
  • ) Close lookbehind
  • [^"]* Match optional chars other than "
  • (?=") Assert " to the right

Regex demo

const regex = /(?<=classes!\((?:"[^"]*",\s*)*")[^"]*(?=")/g;
const str = `classes!("text-xl", "text-blue-500")
String::from("test")
classes!("text-sm")
`;
console.log(str.match(regex))
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