Search code examples
regexregex-group

Regex for finding match groups for 1 backtick and 3 backtick


I'm trying to come up with a regex that matches the insides of a backtick, either 1 or 3.

I have the following regex that works for 1 backtick:

`(.*?)`

and this one works with 3:

```(.*?)```

I want to combine them into one regex search, I've tried something like

(`|```)(.*?)(`|```)

But that creates too many match groups, I've tried $ and ^, but those seems to be start of a line and end of a line...

Edge case 1:

My SQL Statement is below:
```
SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 1";
```

should have 1 group with:

SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 1";

Edge case 2

My SQL Statement is below:
```
SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 1";
```

```
SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 2";
```

Should have 2 groups:

SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 1";

and

SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 2";

Edge case 3

My SQL Statement is below:
```
SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 1";
SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 2";
```

Should have 1 group:

SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 1";
SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 2";

Should put the entire block in a group


Edge Case 4

SQL_STATEMENT = "SELECT * FROM `table` WHERE `id` = 1";

Should have 2 groups

table

and

id

Solution

  • Capture either 1 or 3 backticks and use a back reference at the end so require them to be balanced.

    Simple version:

    (`(?:``)?)([^`]+)\1
    

    Balaced only version. (ie the number of backticks is the same at start and end)

    (?<=[^`]|^)(`(?:``)?)([^`]+)\1(?=[^`]|$)
    

    Your target (the contents) are in group 2

    See live demo.