0

I need to extract with regex one value and if not found extract another.

<notificationNumber>0373100023320000078</notificationNumber>
    <lotNumber>1</lotNumber>
    <placing>12011</placing>
    <purchaseCode>201770801462077300100101610014520244</purchaseCode>
    <contractProjectNumber>03731000233200000780001</contractProjectNumber>
    <tenderPlan2020Info>
        <ns3:plan2020Number>202003731000233001</ns3:plan2020Number>

I wrote next regexp: purchaseCode>(.*?)<|plan2020Number>(.*?)<

It works fine in online regexp editors. And work fine in dart:

  final regex = RegExp(r'purchaseCode>(.*?)<|plan2020Number>(.*?)<');
  final match = regex.firstMatch(fileContent);  

Only with first expression. But if I changing code to:

final regex = RegExp(r'purchaseCode123>(.*?)<|plan2020Number>(.*?)<');

If do not process second part: plan2020Number>(.*?)<

Full code:

void main() {

String str = """<notificationNumber>0373100023320000078</notificationNumber>
    <lotNumber>1</lotNumber>
    <placing>12011</placing>
    <purchaseCode>201770801462077300100101610014520244</purchaseCode>
    <contractProjectNumber>03731000233200000780001</contractProjectNumber>
    <tenderPlan2020Info>
        <ns3:plan2020Number>202003731000233001</ns3:plan2020Number>""";
  
  final regex = RegExp(r'purchaseCode123>(.*?)<|plan2020Number>(.*?)<');
  final match = regex.firstMatch(str);  
  print(match?.group(1)); // second match do not works
  
}
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145
  • 1
    You use `firstMatch` to get the first match only. Use `allMatches`, `regex.allMatches(str).map((z) => z.group(1))` – Wiktor Stribiżew Sep 15 '22 at 08:59
  • And notice that the RegExp has two capture groups, so you need to use `[2]` (the recommended syntax for `.group(2)`) for the second match. Try `RegExp(r"(?:purchaseCode|plan2020Number)>(.*?)<")` instead. – lrn Sep 15 '22 at 15:03

0 Answers0