Regex capture without surrounding white spaces

Hello to all,

I appreciate I can remove the whitespace after I extract with regex but was hoping someone could provide a regex to capture without the leading and trailing whitespaces in the first place.

(?<=Name\s?:).*(?=Date)

Name:James Date : 09/04/22

Name : Mary Date : 09/04/22

Name : Tom Date : 09/04/22

Address : America Date : 09/04/22

Address : United Kingdom Date : 09/04/22

Screenshot 2022-04-09 143315

Hi @MikeC ,

Could you give this pattern a try?

image

System.Text.RegularExpressions.Regex.Matches(str_txtData,"(?<=Name\s?\:(\s+)?)[A-z]+(?=(\s+)?Date)")

image
IgnoreSpaces.xaml (5.9 KB)

Kind Regards,
Ashwin A.K

Thank you very much, works perfectly :blush:
Im sure I can reuse that in many other scenarios.

Thanks again.

We would recommend to reduce the complexity to the pattern and just trim the match result

Hi Peter,

Im sorry if I didnt explain but I was just looking for values preceded by Name.
However the regex you provided is equally beneficial for further use cases so thank you also, much appreciated.

Actually, would you recommend getting the value even if theyre are whitespaces before/after and then trimming ?

Thank you.

Hi @MikeC ,

I would recommend using the Trim Method because it takes care of all the whitespaces, regardless of whether its positioned on the Left or on the Right →

image

Another reason, is because it reduces complexity.
Your pattern is fine @MikeC the way it is, just make it a habit to Trim it while calling it.

Kind Regards,
Ashwin A.K

Thanks to all and for the feedback, will concentrate on keeping the regex simple and then trimming rather than an overly complicated regex.

Thanks guys :grinning:

@MikeC
find attached demo for simple pattern and trimming also more trim chars
grafik

Thank you very much, very helpful :ok_hand:

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.