Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace asterisk characters with html bold tag

Does anyone have a good regex to do this? For example:

This is *an* example

should become

This is <b>an</b> example

I need to run this in Objective C, but I can probably work that bit out on my own. It's the regex that's giving me trouble (so rusty...). Here's what I have so far:

s/\*([0-9a-zA-Z ])\*/<b>$1<\/b>/g

But it doesn't seem to be working. Any ideas? Thanks :)

EDIT: Thanks for the answer :) If anyone is wondering what this looks like in Objective-C, using RegexKitLite:

NSString *textWithBoldTags = [inputText stringByReplacingOccurrencesOfRegex:@"\\*([0-9a-zA-Z ]+?)\\*" withString:@"<b>$1<\\/b>"];

EDIT AGAIN: Actually, to encompass more characters for bolding I changed it to this:

NSString *textWithBoldTags = [inputText stringByReplacingOccurrencesOfRegex:@"\\*([^\\*]+?)\\*" withString:@"<b>$1<\\/b>"];
like image 392
Adam Avatar asked May 31 '11 01:05

Adam


4 Answers

Why don't you just do \*([^*]+)\* and replace it with <b>$1</b> ?

like image 74
nickytonline Avatar answered Nov 04 '22 19:11

nickytonline


You're only matching one character between the *s. Try this:

s/\*([0-9a-zA-Z ]*?)\*/<b>$1<\/b>/g

or to ensure there's at least one character between the *s:

s/\*([0-9a-zA-Z ]+?)\*/<b>$1<\/b>/g
like image 22
Andrew Cooper Avatar answered Nov 04 '22 20:11

Andrew Cooper


I wrote a slightly more complex version that ensures the asterisk is always at the boundary so it ignores hanging star characters:

/\*([^\s][^\*]+?[^\s])\*/

Test phrases with which it works and doesn't:

enter image description here

like image 28
Sheharyar Avatar answered Nov 04 '22 19:11

Sheharyar


This one regexp works for me (JavaScript)

x.match(/\B\*[^*]+\*\B/g)  
like image 1
Vadim Avatar answered Nov 04 '22 20:11

Vadim