Home > Software design >  Regex that match for a string that starts and ends with specific character
Regex that match for a string that starts and ends with specific character

Time:01-02

I'm in the process of migrating our rich text editor and I'm in need of a regex that will match this kind of string.

valid -> ```string```
invalid -> string```
invalid -> ```string

basically need to look for string enclosed with "```"

I had this regex but it looks for either and not both, I know that it looks for either because of the pipe, but I cannot find and docs on how to use "&" operator on a regex.

\`{3}$|^\`{3}

CodePudding user response:

Why don't you just match all text in-between with .*?

\`{3}.*\`{3}

CodePudding user response:

If I understand correctly, you're trying to match the shortest string enclosed in

```

The most simple approach would be:

(?<=\`{3})(. ?)(?=\`{3})

This matches the shortest enclosed string without including the enclosure in the matching group.

The ? in . ? is there to ensure matching the shortest sequence possible.

This is called a positive lookbehind:

(?<=\`{3})

This is called a positive lookahead:

(?<=\`{3})

Try it yourself: https://regex101.com/r/ZPGHVd/1

CodePudding user response:

As You mentioned that you are trying to check for exactly

```  ```

and this can help you with that

\`{3}\w*\`{3}$

OR

\`{3}.*\`{3}
  • Related