1

i have a string like this :

"xxxxxxx File_6547845_Whateverishere_S_Md.Txt yyyyyyyyyyyyy File_14787547_Whateverishere_S.Txt zzzzzzzzzzzzz"

and i want to only match the String that start with "file_number_text" and ends with "_s.txt" NOT "_S_md.txt"

i tried "file_\d+?_.*?_s(?!_)\.txt"

but always match String begins with "File_6547845" contains "yyyyyy" and ends with "_s.Txt"

Rocket_13
  • 13
  • 3

1 Answers1

0

If your file paths cannot contain spaces, just use a more specific pattern insteaf of .*?, say, \S*, 0+ non-whitespace chars:

/file_\d+_\S*_s\.txt/i

See this regex demo

If there can be spaces inside the path, it will be very difficult to come up with a safe pattern. Perhaps, matching anything but the .txt substring can help:

/file_\d+_(?:(?!\.txt).)*_s\.txt/i

See this regex demo, where (?:(?!\.txt).)* matches any 0+ chars that do not start the .txt substring. So, this pattern will go up to the last .txt it can find on the line, and then will backtrack looking for _s.txt. If not found, the match will fail, else, the match will be returned.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563