Skip to content

Matching basics

Amy Brennan-Luna edited this page Aug 6, 2020 · 5 revisions

BEX Matching is a structured code matching library to assist with finding and replacing code

You're likely already familiar with the idea of structured code.

For example,

if (value == 1) {
  System.out.println("You're #1");
}

You'll likely recognize that as an if branch. How do you know it's an if branch? Well, it has the structure of an if branch.

if (condition) { stuff }

The structure focuses on the big picture and gives flexibility for the details. For example, the braces may be on the same line as the if condition; they may be on different lines. The code could be indented with spaces, tabs, or there may be no indention.

Imagine writing a regular expression to parse this out. You'd have to deal with one big challenge - balanced parenthesis and braces. Regular expressions were designed for text, not code. This is what makes structured code matching unique; it ensures everything is balanced, without you having to tell it.

To describe the above if branch, you'd use the following pattern

if (:[condition]) { :[stuff] }

Notice how the above pattern looks just like the structure we mentioned earlier. In this case, :[condition] is a capturing group, named condition. Just like in regex, this capture group can be used while iterating over the matches or as part of a replacement.

The other thing you may notice is we didn't have to escape anything, whereas in regex we would (such as the parentheses). Structured matching allows us to specify exactly what we mean, keeping the syntax clean.

This is just a taste of what structured matching can do. Next, we'll explorer some examples and then dive into the syntax available

Clone this wiki locally