Quantcast
Channel: A Curious Animal » Tools
Viewing all articles
Browse latest Browse all 11

Greedy and Nongreedy Matching in a Regular Expression

$
0
0

This questions has come to me many times so it is time to write a post that acts as a reminder.

Currently I have a string like

ftp://user:password@server/dirA/dirB/file

and what i want is parse it to get the user, password, server and path to the file (/dirA/dirB/file). My first try was:

ftp://(\S+):(\S+)@(\S+)(/\S+)

but that returns me server=server/dirA/dirB, which isn’t what I want. The idea is that the group after the @ would make a non gready match. This is achieved using the ? char. So the final and right regular expression will becomes:

ftp://(\S+):(\S+)@(\S+?)(/\S+)

which returns server=server and file=/dirA/dirB/file.

Related Posts:


Viewing all articles
Browse latest Browse all 11

Trending Articles