Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

disallow character if not prefixed with another character using regex

I have incorporated the following regular expression into my code:

.gsub(/(^|[^*])(\*\*)([^*]+)(\*\*)($|[^*])/m, '\1*\3*\5') # bold

The issue I’m facing is that the \3 block (defined as [^*]+) doesn’t currently permit asterisks * within the text.

My objective is to modify the regular expression in such a way that it allows asterisks only if they are preceded by an escape character \. What is the appropriate approach to achieve this modification?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

examples: **hello \* world** i want it to output *hello \* world*

but i got the text with no change with the current regex

>Solution :

In these situations, you can use an unrolled [^*\\]*(?:\\.[^*\\]*)*:

.gsub(/(^|[^*])(\*\*)([^*\\]*(?:\\.[^*\\]*)*)(\*\*)($|[^*])/m, '\1*\3*\5') # bold

See the regex demo. Which can be further optimized to

.gsub(/(?<!\*)\*\*([^*\\]*(?:\\.[^*\\]*)*)\*\*(?!\*)/m, '*\1*') 

See this regex demo

Details:

  • (?<!\*) – a position that is not immediately preceded with a *
  • \*\* – a ** string
  • ([^*\\]*(?:\\.[^*\\]*)*) – Group 1: any zero or more chars other than \ and * and then zero or more sequences of a \ char followed by any other char and then zero or more characters other than * and \
  • \*\* – a ** string
  • (?!\*) – a position that is not immediately followed with a *

See the Ruby demo:

text = '**hello \* world**'
puts text.gsub(/(?<!\*)\*\*([^*\\]*(?:\\.[^*\\]*)*)\*\*(?!\*)/m, '*\1*') 
# => *hello \* world*
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading