Jump to content

Find the last occurrence of a character


dontpanic

Recommended Posts

I'm trying to match something along the lines of: "name-username:password@server," and I can do that with this regex:

 

$pattern = '/(?P<name>\w+)-(?P<username>\w+)?P<password>\w+)@(?P<server>\w+)/' 

But things start going wrong with a password that contains one of the delimiter characters. I could change the password \w+ to something more specific ([a-zA-Z0-9!@#$^&*()_-=+]) but something in my gut tells me thats not right. I don't have enough experience with regular expressions to tackle this and was wondering if anyone here has any ideas. This format (other than the first '-') is commonly used when logging into websites, so I imagine its been parsed before. I think I need a sort of greedy negative look-behind, but I just can't seem to grasp how to go about it.

 

Thanks in advance for your help!

 

Update: here is a list of non-alphanumeric characters that passwords may contain : ~!@#$%^&*()_+{}|:"<>?/.,';\][=-`)

Link to comment
Share on other sites

That got me closer, but not quite there...

 

$pattern = '/(?P<name>^[^-]+)-(?P<username>[^:]+)?P<password>[^@]+)@(?P<server>.*$)/';
$subject = 'name-username:p@ssword@server';
preg_match($pattern, $subject, $matches);
print_r($matches);

 

yields

 

Array
(
    [0] => name-username:p@ssword@server
    [name] => name
    [1] => name
    [username] => username
    [2] => username
    [password] => p
    [3] => p
    [server] => ssword@server
    [4] => ssword@server
)

 

I do feel like we're really close though...

Link to comment
Share on other sites

ups try

$pattern = '/(?P<name>^[^-]+)-(?P<username>[^:]+)?P<password>.+)@(?P<server>[^@]+$)/';
$subject = 'name-username:p@ssword@server';
preg_match($pattern, $subject, $matches);
print_r($matches);
?>

 

That did it! I can't believe how much I was over thinking that ":<password>-" part. Thanks a ton, sasa!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.