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
https://forums.phpfreaks.com/topic/219220-find-the-last-occurrence-of-a-character/
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...

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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.