Search code examples
regexrpa

How do I find the first occurrence of "&" in a string using regex?


I have a set of data and each row has different number of &. How do I find and match the first & in each row using regex?

Sample data:

  1. Document & saved (faulty authorization)
  2. Document & cannot be processed in this transaction with billing type &
  3. Revenue of leading WBS element & determined by substitution from &

I am working on a RPA system and when I put & as regex, it matches all & occurrences instead of the first.

So wonder if you guys have any alternatives.

Thanks!


Solution

  • Since the regex engine you are using is .NET, you may use a positive lookbehind based solution:

    (?<=\A[^&]*)&
    

    See the regex demo.

    Details

    • (?<=\A[^&]*) - a location in the string that is immediately preceded with
      • \A - start of string
      • [^&]* - 0 or more chars other than &
    • & - a & char.