Regex - Take format without strings around

Asked

Viewed 135 times

3

I’m trying to do a regex to get Slack formatting.

Ex.: *a* => Take it to make bold

An initial regex I did was:

/\*(.*?)\*/g

The problem:

  • Can’t have anything around the string(No character stuck before or after)
  • Could be the beginning of the line

Situations that should work:

*a*
a *a* a

Situations that NAY should work:

b*a*
*a*b
*a**
**a*

1 answer

4


1) Searching for the asterisks: \*([^\*]+?)\*(?!\*)

2) Adding tags to bold: <strong>$2</strong>

Now just apply in your project:

let str = 'Lorem *ipsum dolor* sit amet, *consectetur** adipisicing elit. Optio repellat ipsa quibusdam ab doloremque accusamus nobis minima maiores voluptas, incidunt rerum alias, aliquam ut minus consequatur odio voluptatibus voluptates exercitationem.';

str = str.replace(/\*([^\*]+?)\*(?!\*)/i, '<strong>$1</strong>');

console.log(str);

@Edit Now it won’t find if you have two asterisks together, with nothing inside.

@edit2 Now it won’t find if you have two asterisks together at the end of the search expression, as recalled @sam (*expressão**). And I improved upon the suggestion of @hkotsubo.

Working example: Regex101.com

  • Putting an asterisk together will work: *ipsum dolor**... But the question says that this situation should not work: *a**.

  • 1

    You better put [^*]+ (qq thing other than asterisk) to avoid backtracking excessive when the second *. See that with .+ regex performs more than 1000 steps until you realize you don’t have a second *, while using [^*]+ she takes less than half - and this increases absurdly as the size of the text.

  • 1

    @Sam fixed! hkotsubo I liked the idea. Updated code!

  • Wow, cool. And there’s a way to avoid that when you have a character on the side, it doesn’t work? Type: a[asterisk]a[asterisk] does not work because of the character attached to it. I need to do this because in Slack it doesn’t work if there is something before or after.

  • 1

    Yes! Search on regex Negative/Positive Lookahead/lookbehind. In this example I used the Negative Lookahead: https://www.regular-expressions.info/refadv.html

  • Vlw for the help!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.