views:

74

answers:

3

This was a fascinating debugging experience. Can you spot the difference between the following two lines?

StringReplace["–", RegularExpression@"[\\s\\S]" -> "abc"]
StringReplace["-", RegularExpression@"[\\s\\S]" -> "abc"]

They do very different things when you evaluate them. It turns out it's because the string being replaced in the first line consists of a unicode en dash, as opposed to a plain old ascii dash in the second line.

In the case of the unicode string, the regular expression doesn't match. I meant the regex "[\s\S]" to mean "match any character (including newline)" but Mathematica apparently treats it as "match any ascii character".

How can I fix the regular expression so the first line above evaluates the same as the second? Alternatively, is there an asciify filter I can apply to the strings first?

PS: The Mathematica documentation says that its string pattern matching is built on top of the Perl-Compatible Regular Expressions library (http://pcre.org) so the problem I'm having may not be specific to Mathematica.

+1  A: 

Here's an asciify function which I used as a workaround at first:

f[s_String] := s
f[x_] := FromCharacterCode[x]

asciify[s_String] := 
  StringJoin[f /@ (ToCharacterCode[s] /. x_?(#>255&) :> "&"<>ToString[x]<>";")]

Then I realized, thanks to @Isaac's answer, that "." as a regular expression doesn't seem to have this unicode problem. I learned from the answers to http://stackoverflow.com/questions/2257884/bug-in-ma that "(.|\n)" is ill-advised but that "(?s)." is recommended. So I think the best fix is the following:

StringReplace["–", RegularExpression@"(?s)." -> "abc"]
dreeves
Interesting reading in the other question/answers you site. Given what's there, I'm inclined to agree that `"(?s)."` is probably better, though as I read those answers, the issue may be limited to `"(.|\n)*"` (with the `*`).
Isaac
+1  A: 

Using "(.|\n)" for the input to RegularExpression seems to work for me. The pattern matches . (any non-newline character) or \n (a newline character).

Isaac
+1  A: 

I would use a StringExpression in place of RegularExpression. This works as desired:

f[s_String] := StringReplace[s, _ -> "abc"]

In a StringExpression, Blank[] will match anything, including non-ASCII characters.

You still have to be careful, though, because other chunks of StringExpression functionality aren't properly Unicode-aware. For example,

In[1]:= StringMatchQ[ToCharacterCode[{945}], LetterCharacter] 

Out[1]= False

In[2]:= LetterQ[FromCharacterCode[{945}]]

Out[2]= True

The documentation for LetterCharacter claims that it matches any character for which LetterQ returns True, but this is a blatant lie.

Pillsy
As noted in the Working with String Patterns tutorial [1] under "RegularExpression versus StringExpression", the string pattern `_` and `RegularExpression["(?s)."]` are equivalent.[1] http://reference.wolfram.com/mathematica/tutorial/WorkingWithStringPatterns.html
Michael Pilat