How to extract year only from a string and assign it to a variable

Strings extracted from a list of strings:
file = C:\Users\SAMUEL CHAANE\Desktop\Sorting_Annual_Reports_Project\nd340-c1-intro-to-uipath-rpa-project-starter-master\Leonard Hofstadter_Report_01012020.pdf

I want to extract the bold part. I tried couple of regex but I am failing

give a try on following pattern:

along with the extension: \d{4}(?=\.[PpDdFf]+)

As we expect only one match you can also use Regex.Match(file,"\d{4}(?=\.)").toString
and can use the statement in short form when System.Text.RegularExpresions is imported:

1 Like

It worked like magic, even if I change the text it still works.
Can you please explain this: "\d{4}(?=.)"

it is anchoring on the dot and looks for 4 digits left from this is helping much on searching a pattern and gives explanations to the statement. Also have a look here:
Regex help tutorial MEGAPOST – Making your first Regex post, Reusable Regex Patterns, Regex Troubleshooting, Sample Workflow and more


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