mtzE
mtzE

Reputation: 57

Regex pattern where end of the String matches

I have the following problem. I want to search for the path of folders and files and my regex should ONLY match if the last part of the path (file or directory) includes my searchstring.

For example:

I want to search for 'hallo' in the following path's:

  1. D:\Users\me\Documents\FindFile\hallo\

  2. D:\Users\me\Documents\FindFile\hallo\bla\

  3. D:\Users\me\Documents\FindFile\hallo\bla\bla 2\

  4. D:\Users\me\Documents\FindFile\hallo\inside\

  5. D:\Users\me\Documents\FindFile\hallo\inside\hallo nr2\

  6. D:\Users\me\Documents\FindFile\hallo\inside\hallo nr2\well hallo.txt

  7. D:\Users\me\Documents\FindFile\test\drin\das hallo\

  8. D:\Users\me\Documents\FindFile\test\drin\hallo test\

  9. D:\Users\me\Documents\FindFile\test\txt drin\test_hallo.txt

Now Path numbers 2, 3 and 4 should NOT be matched because they don't end with a 'hallo' in it. (For example 2 ends with 'bla' and not with 'bla hallo' or something that has 'hallo' in it)

I'm currently trying this with this regex: .*hallo(\\|.+) but it's not working.

You can check what I've done here. Lines 2 ,3 and 4 are highlighted and should be not: https://regex101.com/r/eF3cU8/1

Upvotes: 0

Views: 60

Answers (2)

SamWhan
SamWhan

Reputation: 8332

If as you say - ONLY match if the last part of the path includes my searchstring - which would mean that example no. 9 shouldn't be matched either, this should do it:

hallo[^\\]*\\[^\\]*$

It matches hallo (your search string), optionally followed by any characters but \. Then followed by a \, and then again optionally followed by any characters but \

Check it out here at regex101.

Upvotes: 1

Keith Hall
Keith Hall

Reputation: 16065

You can use:

^.*hallo(?=\\$|[^\\]+).*$

Demo

  • ^ anchor at the start of the line (we are using the m flag)
  • .* any number of occurrences of any character
  • hallo the literal text hallo
  • (?=\\$|[^\\]+) a positive lookahead to confirm that either the next character is a slash followed by the end of the line, or there are no more slashes on the line
  • .* any number of occurrences of any character
  • $ the end of the line

Upvotes: 1

Related Questions