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 – get everything between two characters based on input

let assume I have string like:
"Today is ((day|12pm))"

what I would like to do now is to get everything between (()) for substring "day" but without the brackets. So the result would be: day|12pm but for another substring like time ((time|moon)) would return time|moon.

I could only came up with something like this:
\(\(\W*day – it gets me ((day which is only part of the string. How to get the other part till )) but without the brackets itself?

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

Thanks.

>Solution :

The regex in JavaScript would look like this

const regex = /\(\(([^)]*)\)\)/

The actual code would be like this

const inputString = "Today is ((day|12pm))";
const regex = /\(\(([^)]*)\)\)/;
const matches = inputString.match(regex);
console.log(matches)

if (matches && matches.length > 1) {
  const result = matches[1];
  console.log(result); // Output: day|12pm
} else {
  console.log("No match found");
}

As matches is containing the array of values. If there is a match then matches[1] extracts the content captured

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