Regex: how to separate username:password?

634 Views Asked by At

Regex: how to separate username:password? I need a code to separate in 2 diferrent lists usernames and passowrds

john:123
place:Abc457

etc.

Final lists:

john
place

etc.

and 2'nd list.txt

123
Abc457

etc.

Well I prefer more the passwords and not necessarily the usernames, Thanks

2

There are 2 best solutions below

1
On

I would use (.*?):(.*). Then you can access the username as group 1 ($1 in substitutions) and the password as group 2.

To create your first textfile use $1 ( http://regexr.com/3b8as )

john
place

To create your second textfile use $2 ( http://regexr.com/3b8av )

123
Abc457
0
On

Ignoring the usernames per your non-need of it, but it'd be trivial to modify the following examples to keep it. Below examples show regex extract and split operations for both Python and Perl.

Python regex:

>>> import re
>>> s = "john:123"
>>> pw = []
>>> pw.append(re.match(r'.*?:(.*)', s).group(1))
>>> pw
['123']

Perl regex:

my $s = "john:123";
my @a;

$s =~ /.*?:(.*)/;
push @a, $1 if $1;

print @a;

Python split:

>>> s = "john:123"
>>> pw = []
>>> pw.append(s.split(':')[1])
>>> pw
['123']

Perl split:

my $s = "john:123";
my @a;

push @a, (split(/:/, $s))[1];

print @a;