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

group numbering when one of them is facultative

I’m coding in Rust but I suppose that my question is kind of language-independent.

For a regex field_name1 (\d+)( facultative_field \d+)? field_name2 (\d+) I’d like to get the values of fields 1 and 2. But number/rank of the group dedicated to field 2 depends on the presence of the group of the facultative field (which makes the extract method panic).

What’s the idiomatic way to get the value of field 2?

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

>Solution :

A regex such as field_name1 (\d+)((?: facultative_field \d+)?) field_name2 (\d+) should work. The change is to put the optional part in a non-capturing group with (?: ... ). Then enclose that whole thing in a capturing group. Thus if the facultative_field part is missing then capture group 2 will be empty. Capture group 3 will allways hold the final digits.

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