Search code examples
regex

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?


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.