3
$\begingroup$

In normal RegEx \l will make the character to the right lowercase. However, it seems like the RegEx in Mathematica does not have this functionality.

For example

StringCases["Abba", RegularExpression["(.).*?\\l\\1"]]

will return the following error message

RegularExpression::msg37: "Mathematica does not support \\L, \\l, \\N, \\P, \\p, \\U, \\u, or \\X in RegularExpression[\!\(\"(.).*?\\\\l\\\\1\"\)]."

Is there some workaround that I can use? Note that (?i) is not sufficient as I need the character to be lowercase only.

Thanks

$\endgroup$
2
  • $\begingroup$ You can use [a-z] if ASCII is sufficient ... otherwise it might not be possible to use regexes and you may need to resort to using string patterns with _?LowerCaseQ which I think will be slower. $\endgroup$
    – Szabolcs
    Commented Oct 28, 2013 at 15:26
  • $\begingroup$ @Szabolcs I believe the tricky part is that \\1 refers to the first byte of the regular expression, which may be also uppercase, but match the lowercase letter at end of the regular expression. $\endgroup$
    – kirma
    Commented Oct 28, 2013 at 15:37

2 Answers 2

2
$\begingroup$

I believe this is what you want.

StringCases["Abba", RegularExpression["(.).*(?=(?i:\\1))[a-z]"]]

(?=(?i:\\1)) is a lookahead which says, "if the next character matches \1 in any case," but then it also has to match the pattern that occupies the place of the next character, which is [a-z] i.e. only lowercase letters.

If it fails to match the outer pair of Aa, it will match the inner pair of bb. I couldn't figure out if this was what you wanted or not, it does seem like it judging from your attempt.

$\endgroup$
2
$\begingroup$

This is not a regular expression (or PCRE), but it's a StringExpression that can be used where RegularExpression qualifies:

StringCases["Abba", 
 x : LetterCharacter ~~ Shortest[___] ~~ 
   y : LetterCharacter /; ToLowerCase[x] == y]

{"Abba"}

LetterCharacters are used instead of _ primarily to keep ToLowerCase meaningful.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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