How to use Regex in Make?

I agree. Regular Expressions can be VERY useful!

In addition to the Text parser module that Bjorn pointed out, you can often just us the replace() function. There are cases, due to the differences in the implementation (like the multiline flag not being allowed), where using the Text parser is basically required. But in all my scenarios I think I have used the Text parser module twice. Everywhere else where I want to use Regex I just use good old replace().

Here is a little info on it from the documentation: String functions

Of course, you can use replace() to, well, replace with Regex. Most often, I use it as Bjorn used the Text parser module in his example, to extract data.

To use it this way requires a little change in perspective. Basically, to extract data, you need to MATCH the entire string, capturing (and replacing) only the part(s) you want.

To extract the same data as in Bjorn’s example using replace() you would get something like this:

replace(<a href="www.google.com">Google</a>;/.*href=\"(.+)\".*/; $1)

Some notes:

  1. In this case the global flag is not required.
  2. The multiline flag is not allowed in replace() (nor needed here)
  3. “$1” refers to the first capture group, the “(.+)” in the middle of the search string.

Jim

4 Likes