3
$\begingroup$

Regular expressions are a very powerful tool, but such expressions are often very cryptic. If you want to understand them, it is best to have colored pencils at hand to color-code the parts that belong together.

Thus, it is obvious to color-code regular expressions in Mathematica already during development, in order to add explanatory texts to the individual colored parts, explaining what they (should) do.

However, it is not possible to use such colored strings in RegularExpression in Mma: One gets then e.g. such an error message:

RegularExpression::msg8 (Range out of order in character class in RegularExpression...)

How can I teach RegularExpression to remove all color attributes contained in its search pattern and then continue as usual?

$\endgroup$
3
  • $\begingroup$ Can you give us a FullForm example of a coloured string? Otherwise we need to guess and implement what you are doing. $\endgroup$
    – mikado
    Jun 22 at 9:35
  • $\begingroup$ Yes, here an example using lookaround on both sides: The search pattern to be caught is highlighted yellow, "(?<=^|\\S)\!(*StyleBox[\")\",Background->RGBColor[1, 1, 0.85]])\!(*StyleBox[\"\\\\\\\\\",Background->RGBColor[1, 1, 0.85]])\!(*StyleBox[\"s\",Background->RGBColor[1, 1, 0.85]])\!(*StyleBox[\"+\",Background->RGBColor[1, 1, 0.85]])\!(*StyleBox[\"-\",Background->RGBColor[1, 1, 0.85]])(?=a+\\.)" $\endgroup$ Jun 22 at 10:24
  • $\begingroup$ The example was from my Example in my question #250007. $\endgroup$ Jun 22 at 10:31
2
$\begingroup$

You can use ExportString[regex, "Text"] to strip away any formatting:

regex = "(?<=^|\\S\!\(\*StyleBox[\")\",Background->RGBColor[1, 1, 0.85]]\)\!\(\*StyleBox[\"\\\\\",Background->RGBColor[1, 1, 0.85]]\)\!\(\*StyleBox[\"s\",Background->RGBColor[1, 1, 0.85]]\)\!\(\*StyleBox[\"+\",Background->RGBColor[1, 1, 0.85]]\)\!\(\*StyleBox[\"-\",Background->RGBColor[1, 1, 0.85]]\)(?=a+\\.)"

enter image description here

plain = ExportString[regex, "Text"]
(* "(?<=^|\\S)\\s+-(?=a+\\.)" *)

StringCases["aaa -aaaa.", RegularExpression@plain]
(* {" -"} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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