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

how to use regex to match everything inside two pair of backticks

this is my text:

`string1` some text `string2` more text `string3`

I want to select all text between two pair of backticks.but only between first and second backticks, which is, string1, and third and fourth backticks which is string2 and fifth and sixth backticks which is string3. in other words between each odd number of backticks and its subsequent even number. so far I got this:

([^`]+)

but this one, selects all the texts between all backticks which is totally undesirable.

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

by the way this problem happens for single and double quote as well.

>Solution :

Answer:

To select text between pairs of backticks where each pair consists of an odd-numbered backtick followed by an even-numbered backtick, you can use the following regular expression:

(?<!`)`([^`]+)`(?!`)

Explanation:

  1. **(?<!\)**: Ensures that the backtick () before the match is not part of another backtick, i.e., it’s not immediately preceded by a backtick.
  2. `([^`]+)`: Matches the content between two backticks.
    • ([^]+)`: Captures one or more characters that are not backticks.
  3. **(?!\)**: Ensures that the backtick () after the match is not part of another backtick, i.e., it’s not immediately followed by another backtick.

Code Examples

In Python:

import re

text = "`string1` some text `string2` more text `string3`"
matches = re.findall(r'(?<!`)`([^`]+)`(?!`)', text)

print(matches)

Output:

['string1', 'string2', 'string3']

In JavaScript:

const text = "`string1` some text `string2` more text `string3`";
const matches = [...text.matchAll(/(?<!`)`([^`]+)`(?!`)/g)];

console.log(matches.map(match => match[1]));

Output:

['string1', 'string2', 'string3']

Notes:

  • If you want to handle similar cases for single or double quotes, simply replace the backtick () in the regex with the respective quote (or") or use a character set like [\'].
  • For multiline strings, make sure to enable the appropriate flag (re.DOTALL in Python, m flag in JavaScript, etc.).

This regex ensures that you only capture the desired text between odd/even backtick pairs.

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