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.
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:
- **
(?<!\)**: Ensures that the backtick () before the match is not part of another backtick, i.e., it’s not immediately preceded by a backtick. `([^`]+)`: Matches the content between two backticks.([^]+)`: Captures one or more characters that are not backticks.
- **
(?!\)**: 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.DOTALLin Python,mflag in JavaScript, etc.).
This regex ensures that you only capture the desired text between odd/even backtick pairs.