Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Why does the following StringReplace pattern match:

StringReplace["blah *hello* blah", ("*" ~~ ShortestMatch[str__] ~~ "*") :> 
    ("<u>" <> str <> "</u>")]
(* blah <u>hello</u> blah *)

but not when bracketing the pattern with WordBoundary:

StringReplace["blah *hello* blah", (WordBoundary ~~ "*" ~~ 
    ShortestMatch[str__] ~~ "*" ~~ WordBoundary) :> ("<u>" <> str <> "</u>")]
(* "blah *hello* blah" *)
share|improve this question
btw, ShortestMatch is now superseded by Shortest – R. M. Oct 20 '12 at 21:38
up vote 5 down vote accepted

It doesn't work because what you want to match is the Whitespace not the Wordboundary. In fact, you really don't need WordBoundary because your "*hello*" is surrounded by Whitespace. This means, if the word you want to match, happens to be at the end of a line, WordBoundary would prevent the match. Therefore, the only thing you need is WhiteSpace

StringReplace["blah *hello* blah", 
 (Whitespace ~~ "*" ~~ Shortest[str__] ~~ "*" ~~ Whitespace) :> 
  (" <u>" <> str <> "</u> ")]

If you realy are keen to use it, you have to take care of the Whitespace too

StringReplace["blah *hello* blah", 
 (WordBoundary ~~ Whitespace ~~ 
    "*" ~~ Shortest[str__] ~~ "*" ~~ 
  Whitespace ~~ WordBoundary) 
 :> (" <u>" <> str <> "</u> ")]
share|improve this answer
No need to use WordBoundary. Try (Whitespace ~~ "*" ~~ Shortest[str__] ~~ "*" ~~ Whitespace) – DavidC Oct 20 '12 at 21:47
Ok great, thanks for all the answers and comments – alancalvitti Oct 20 '12 at 21:48
@DavidCarraher I know. Look at my first code block. I just wanted to make clear how it would work with WordBoundary.. – halirutan Oct 20 '12 at 21:49
You might want to mention this in your answer. – DavidC Oct 20 '12 at 21:50
@DavidCarraher I thought Whitespace not the Wordboundary. in my first sentence was enought. Let me make it clearer. – halirutan Oct 20 '12 at 21:51

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.