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>"];
Why don't you just do \*([^*]+)\*
and replace it with <b>$1</b>
?
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
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:
This one regexp works for me (JavaScript)
x.match(/\B\*[^*]+\*\B/g)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With