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?
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*