Tuesday, 15 January 2013

regex negation - Extract Multiple values from a content using regular expression in perl -



regex negation - Extract Multiple values from a content using regular expression in perl -

i have content like:

"emailaddress":"akashu87@gmail.com","username":"akash udupa","active":true,"emailaddress":"coolrohit@rediffmail.com","username":"rohit hegde","active":true,"emailaddress":"manohar_k@rediffmail.com","username":"manohar karnam","active":true,"emailaddress":"satishgk@hotmail.com","username":"satish gk","active":true

i want display values of username in csv file through perl following:

akash udupa rohit hegde manohar karnam satish gk

i sure guys inquire me have tried. problem new perl. can help me perl code? please.

thanks in advance.

there 2 ways this; right way, , fragile way. since json has braces , brackets stripped away, you've started downwards path fragile way:

my $string = q{"emailaddress":"akashu87@gmail.com","username":"akash udupa","active":true,"emailaddress":"coolrohit@rediffmail.com","username":"rohit hegde","active":true,"emailaddress":"manohar_k@rediffmail.com","username":"manohar karnam","active":true,"emailaddress":"satishgk@hotmail.com","username":"satish gk","active":true}; while ( $string =~ m/"username"\s*:\s*"([^"]+)"/g ) { print "$1\n"; }

this anchors "username" tag, , allows whitespace (but not require it) between tag , value. looks double-quote, , captures until next quote $1.

a brief introduction perl's regexes contained in perlrequick, comes perl. regex solution doesn't utilize constructs not explained in document. matter of fact, perlintro, should considered required reading perl users, provides info sufficient task.

since it's possible logic stripped away json might have broken something, , since json might perchance throw @ our one-off regular look isn't equipped handle, wise revert original un-adulterated json, , parse proper parser, this:

use json; $json = <<'eojson'; [ { "emailaddress": "akashu87@gmail.com", "username": "akashudupa", "active": true }, { "emailaddress": "coolrohit@rediffmail.com", "username": "rohithegde", "active": true }, { "emailaddress": "manohar_k@rediffmail.com", "username": "manoharkarnam", "active": true }, { "emailaddress": "satishgk@hotmail.com", "username": "satishgk", "active": true } ] eojson print "$_->{username}\n" @{decode_json($json)}

if json module heavy-weight you, @ json::tiny, minimal, tested, , free of dependencies.

both regex , parser approach work original json, may find code can simplified eliminating section strips brackets , braces original json. 1 time you've done that, json parser solution can 1 line of code. it's lucky day when removing code can create code more robust without removing features.

perl regex-negation

No comments:

Post a Comment