We can use group numbers to reuse the same piece of code while inside regex string, like that:
StringCases["x = y", RegularExpression["([\\w\\s]+)=(?1)"]]
{"x = y"}
To make it more readable and robust (like avoiding the situation when the groups can be renumbered either internally or through a redesign of the regex code), we can name patterns (and yes, (?
syntax works as well as (?P
):
StringCases["x = y", RegularExpression["(?[\\w\\s]+)=(?&var)"]]
StringCases["x = y", RegularExpression["(?P[\\w\\s]+)=(?P>var)"]]
{"x = y"}
{"x = y"}
Perfect so far. However, what if I want to use the groups in the replacement rule? This works:
StringCases["x = y", RegularExpression["([\\w\\s]+)=((?1))"] :> {"$1", "$2"}]
{{"x ", " y"}}
But this doesn't:
StringCases["x = y", RegularExpression["(?[\\w\\s]+)=(?(?&var))"] :> {"${var}", "${rhs}"}]
{{"${var}", "${rhs}"}}
Of course, I can still use the numbers to refer to the groups:
StringCases["x = y", RegularExpression["(?[\\w\\s]+)=(?(?&var))"] :> {"$1", "$2"}]
{{"x ", " y"}}
But this is exactly what I want to avoid. I want to use the names, as they won't be affected by the code redesign.
I also tried $+{name}
, \g
, but they all don't work.
So, the question is: can we use names of the groups in the replacement rule?
Answer
Unfortunately, this is not an answer to the problem but rather some information on the subject that is hopefully of interest. As I said in my comment, one way to solve this issue is to transfer the regex into a StringExpression
.
StringCases["x = y",
x : ((WhitespaceCharacter | LetterCharacter) ..) ~~ "=" ~~ y__ :> {x,y}
]
The above code should be equivalent to your regex. What might be of interest for you is how Mathematica handles the named patterns. For this, we can use the undocumented function StringPattern`PatternConvert
(undocumented, but you can access its full implementation which is very enlightening).
StringPattern`PatternConvert[
x : ((WhitespaceCharacter | LetterCharacter) ..) ~~ "=" ~~ y__]
(* {"(?ms)((?:[[:space:][:alpha:]])+)=(.+)", {{Hold[x], 1}, {Hold[y], 2}}, {}, Hold[None]} *)
Interestingly, you see that Mathematica converts it into a regex with normal grouping and stores the mapping between the groups and the names you gave. Therefore, it knows that x
belongs to the first group.
How this helps you? It probably doesn't. As far as I can see there is no function to automatically turn a regex into a string expression.
Comments
Post a Comment