consider I have a text like :
Some text 1
`special text`
Some text 2
I can get "special text" with regex, but I want other parts of the text too as an array, something like this :
[
Some text 1,
special text,
Some text 2
]
I’ve tried below pattern, but I think it’s not the answer
/(.*)`(.*)`(.*)/gm
4
Answers
We can try using the following regex pattern:
This pattern says to match:
.*?
a term inside backticks|
OR.+
any other contentThe trick here is to eagerly first try to find a backtick term. Only that failing, we consume the rest of the line.
([^`]+): Matches any text that is not within backticks.
`([^`]+)`: Matches text within backticks.
It doesn’t appear you need a regex for this. To create the array,
split()
the string by the newline entity, after removing the extra`
characters:If you want any text between the backtick at the start and the end of the string, you could use replace with a capture group
(.*)
If there can not be any backticks in between, you can use a negated character class
[^`n]
to exclude matching a backtick (and a newline if you don’t want to cross lines):If there can be multiple matches in a single line, and assuming there are no other single backticks and a lookbehind is supported in your environment, you could match either all chars other than a backtick
[^`n]+
or match the same but then between backticks(?<=`)[^`n]*(?=`)
using lookarounds: