Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map a regular expression to its matched text in ripgrep?

If we run ripgrep against a file/directory and pass it a file containing a list of regexes such as:

regexes.txt

pattern1
pattern2
pattern3

The ripgrep successfuly shows all the texts which matched with the regexes. But what if I want to know what specific regex a text matched to? In other words, how to map a regex to its matched text?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The output should look something like:

<pattern> <separator> <matched-text>
<pattern> <separator> <matched-text>

I understand that one way is to spawn multiple subprocesses of ripgrep, searching for one regex at a time. But I am looking for a way to achieve it with a single process using ripgrep CLI.
Would be glad if someone knows a way around.

To summarize my question, How run a ripgrep command and print matches along with regex they matched to?

>Solution :

ripgrep author here. You generally can’t achieve what you want. ripgrep very specifically does not expose which pattern matched. ripgrep itself doesn’t even know which pattern matched.

ripgrep’s regex engine has recently grown the ability to determine which pattern matched, but there aren’t any plans (at time of writing) to expose that functionality in ripgrep proper. But, that does mean you could write a Rust program to do what you want while using the same regex engine that ripgrep uses.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading