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

@samuel.chaane
give a try on following pattern:

\d{4}(?=\.)
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:
grafik

1 Like

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

@samuel.chaane
it is anchoring on the dot and looks for 4 digits left from this

Regex101.com 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

2 Likes

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