javascript - Why is non-greedy character not acting 'non-greedy'? -
I am working with a regex in javascript.
I have this regex: /
and this string:
/ path / to / file
I hope to get the
/ file as a result, but instead getting the whole string back. What do I not understand here?
? should be made of
+ non-greedy, which means it will match some of the most possible characters.
Regular expression will always try to match from left to right even if . +? is non-greedy, however, if possible it will try to match the beginning of the string and will only advance the situation in the event of failure of the match.
You have a few options to fix this:
- Include a greedy match at the beginning of the ragge so that your mail always starts in the string as possible and a capturing What group do you want to hold here can be regex like
/.* (\ /. +?) $ / , and then you get the first code as the group's content as / File will be
Change regex to . +? could not match any of the additional / , so it should be / \ / [^ \ /] + $ / .
Comments
Post a Comment