0

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.

7

1 Answer 1

1

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*
Sign up to request clarification or add additional context in comments.

7 Comments

i didn't get the expected output with this regex, i added an example if the question was not clear.
Also, consider gsub(/(?<!\*)((?:\*\*)*)\*\*([^*\\]*(?:\\.[^*\\]*)*)\*\*((?:\*\*)*)(?!\*)/, '\1*\2*\3') for more complex scenarios. The \ns in the demo are just for line-by-line demo.
and thanks for the demo, I will have a look at it
@OmarFareed That does exactly what you asked for. See regex101.com/r/gDCCI6/6. I also added a Ruby demo.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.