You can use a regular expression to extract the last occurrence of text between parentheses. Here’s a suitable regex pattern for your requirement:
\([^()]*\)(?!.*\([^()]*\))
This pattern captures the text within the last set of parentheses in the string.
Here’s a brief explanation of how it works:
\(: Matches the literal opening parenthesis. [^()]*: Matches any character except for parentheses, zero or more times. \): Matches the literal closing parenthesis. (?!.*\([^()]*\)): Negative lookahead to ensure that there are no more sets of parentheses after the current match.
Can you try RegexOption.RightToLeft as the following?
System.Text.RegularExpressions.Regex.Match(" Swed AB (Public) (52155286HGPU). Could you review","(?<=\()\w+(?=\))",System.Text.RegularExpressions.RegexOptions.RightToLeft).Value
There are multiple regex you can use to solve the problem
Try one of the below and let me know how that works out
Option 1: Using a simple group within parentheses
((\d+[A-Z]+))
Explanation:
(: Matches an opening parenthesis.
\d+: Matches one or more digits.
[A-Z]+: Matches one or more uppercase letters.
): Matches a closing parenthesis.
(\d+[A-Z]+): Captures the delivery code within parentheses.
Option 2: More specific for delivery codes
((\d{8}[A-Z]{4}))
Explanation:
\d{8}: Matches exactly 8 digits.
[A-Z]{4}: Matches exactly 4 uppercase letters.
The rest matches as described in Option 1.
Option 3: Non-greedy match for content in parentheses
((\d+[A-Z]+?))
Explanation:
+?: Ensures the match is non-greedy, extracting the shortest possible match within parentheses.
Option 4: Match only codes that follow a pattern
((\d{8}[A-Z]{4}))
Explanation:
This approach enforces an exact structure for the code, assuming all codes follow the format of 8 digits followed by 4 letters.
Option 5: Flexible match for nested parentheses
([^()]((\d+[A-Z]+))[^()])
Explanation:
Handles cases where parentheses are nested (e.g., Swed AB (Public) (52155286HGPU)).
[^()]*: Matches any characters except parentheses to avoid confusion with nesting.