skip to Main Content

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


  1. We can try using the following regex pattern:

    `.*?`|.+
    

    This pattern says to match:

    • .*? a term inside backticks
    • | OR
    • .+ any other content

    The trick here is to eagerly first try to find a backtick term. Only that failing, we consume the rest of the line.

    var input = `Some text 1
    `special text`
    Some text 2`;
    
    var matches = input.match(/`.*?`|.+/g)
                       .map(x => x.replace(/^`|`$/g, ""));
    console.log(matches);
    Login or Signup to reply.
  2. ([^`]+): Matches any text that is not within backticks.

    `([^`]+)`: Matches text within backticks.

    const text =  'Some text 1 `special text` Some text 2';
    
    const regex = /([^`]+)|`([^`]+)`/g;
    const matches = [];
    let match;
    
    while ((match = regex.exec(text)) !== null) {
      matches.push(match[1] || match[2]);
    }
    
    console.log(matches);
    Login or Signup to reply.
  3. 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:

    const input = `Some text 1
    `special text`
    Some text 2`;
    
    const output = input.replaceAll("`", "").split(/n/g);
    console.log(output);
    Login or Signup to reply.
  4. 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 (.*)

    const regex = /^`(.*)`$/gm;
    const str = `Some text 1
    `special text`
    Some text 2`;
    
    console.log(str.replace(regex, `$1`).split("n"));

    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):

    const regex = /^`([^`n]*)`$/gm;
    const str = `Some text 1
    `special text`
    Some text 2`;
    
    console.log(str.replace(regex, `$1`).split("n"));

    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:

    const regex = /[^`n]+|(?<=`)[^`n]*(?=`)/gm;
    const str = `Some text 1
    `special text`
    Some text 2`;
    
    console.log(str.match(regex));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search