In general no.
The information we seek to extract by using a pattern to recognise interesting parts of a string usually discards much of the string contents.
This is much less apparent in simple patterns like: /abc|def/
as they match a whole string and they are either this or that.
But most interest patterns eg: /\((\d{2})\) (\d{4}) (\d{4})|\+(06\d{2}) (\d{4})(\d{4})/
discard information relevant to the format. Both of these patterns recognise and extract 10 digits but under two different formats: (xx) xxxx xxxx
and +06xx xxxxxxxx
. When reversing this pattern which output format should be selected?
And we haven't even gotten into contextual formatting. Humans love contextual formats. Have you ever wondered why English sentences start with a Capital? Why a phone number shared between two locals might be 6 or 8 digits long, yet sending that number internationally adds and even changes some of the digits?
But to something more hum drum, where do you put the {
after an if
statement?
if (condition) {
}
if (condition)
{
}
if (condition)
{
}
if (condition)
{
}
It still holds the same semantic meaning in most languages, yet this is information the pattern needs to know about in order to generate the correct string.
The reason for this problem is that each Pattern describes a Language. That Language is a subset of all possible strings. To take the /abc|def/
example, it contains two strings: abc
and def
every other string is not part of the language.
To read this language we ask the very simple question, is this string 'some string'
a member of that language? A Boolean answer is the result: yes or no.
To reverse this process and write we have to select one of these strings. In the /abc|def/
example its pretty simple it can only be one of those two strings. Yet we have already hit our first sticking point, which string? The problem is that this pattern was built for recognition, not for generation.
Conversely, what about this pattern: "{0,-30}"
? Formatting using this pattern is trivial, take the text from the first input, align it to the left, and ensure that 30 characters are displayed, padding out the rest as necessary. But what string is in this language?
It is possible to merge the two but it is often unweildly, most languages that make the attempt keep the recognition pattern and the formatting pattern separate such as in Sed.
"#{m[0]}:#{m[1]}@#{m[2]}"
to both generate both the full regex, and to interpolate your strings.