0

I am trying to narrow down a string and find all of the paths.

pathRegex = re.compile(r"^([cC]?[:]?\\)([\a-zA-Z0-9]*)$\S")

mo = pathRegex.findall(r"I have two paths. First is C:\Users\patrick 
and the other is C:\Users\patrick\documents.")

But the output I keep getting is:

['C:\\Users\\pgrimm and the other is C:\\Users\\pgrimm\\documents.']

How do I change the Regex so that it just finds the paths and not the middle text?

  • You could rely on "C:\" (or similar) to get the second path but how can your program possibly tell that "and the other is" isn't part of the path? – 41686d6564 Apr 11 '20 at 17:55
  • @AhmedAbdelhameed I was hoping that the \S would not allow any white space, thus stopping it and preventing it from adding the middle text. – pman312 Apr 11 '20 at 18:25
  • If you are certain that the path doesn't contain a space, then yes it's possible to extract the two paths. You are aware that paths and filenames may contain spaces though, right? – 41686d6564 Apr 11 '20 at 18:31
  • @AhmedAbdelhameed Yes, I am very new to learning programming so I am trying to create random situations in my head and then code them. Could you show me what the regex would need to be if I knew there were no spaces? – pman312 Apr 11 '20 at 18:36
  • Well, for a start, don't use `^` and `$` here. They assert position at the beginning/end of the string, so you only want to use them when you want to match the whole string. There are many other problems with your pattern that I can't address in a comment. So, that aside, you may start with something like `[Cc]:\\\\\S+` ([demo](https://regex101.com/r/YPAdaN/1/)) which will match "C:\\" followed by any number of non-whitespace characters. But then, it'll include invalid path characters so you might want to exclude those. How to do that? Well,.. – 41686d6564 Apr 11 '20 at 18:47
  • ...you should find a good regex tutorial and learn the basics. You may start [here](https://www.regular-expressions.info/quickstart.html), check [this Python regex tutorial](https://www.tutorialspoint.com/python/python_reg_expressions.htm), and check [this reference](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) to search for specific problems. You may also use [regex101 website](https://regex101.com/) for testing your patterns. Good luck! – 41686d6564 Apr 11 '20 at 18:47
  • @AhmedAbdelhameed Thank you! – pman312 Apr 11 '20 at 19:07

0 Answers0