Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Answer: How do I put bracket on substring(s) of a string?

( #710418=categorized answer: print w/ replies, xml ) Need Help??

Q&A > strings > How do I put bracket on substring(s) of a string? contributed by Roy Johnson

#!perl use strict; use warnings; my @testdata = (['CCCATCTGTCCTTATTTGCTG', [qw(ATCTG ATTTG)]] ,['ACCCATCTGTCCTTGGCCAT', [qw(CCATC)]] ,['CCACCAGCACCTGTC', [qw(CCACC CCAGC GCACC)]] ,['CCCAACACCTGCTGCCT', [qw(CCAAC ACACC)]]); for (@testdata) { my ($str, $pats) = @$_; print put_bracket($str, @$pats), "\n"; } sub put_bracket { my $str = shift; # Combine multiple match strings into alternations my $rx = join '|', @_; my @brackets; # Store bracket points for every match while ($str =~ /(?=($rx))/g) { push(@brackets, [$-[0], length($1)+$-[0]]); } # Condense overlapping brackets for my $i (0..$#brackets-1) { if ($brackets[$i][1] >= $brackets[$i+1][0]) { $brackets[$i+1][0] = $brackets[$i][0]; @{$brackets[$i]} = (); } } # Apply the brackets (from back to front) while (@brackets) { my $b = pop @brackets; next unless @$b; substr($str, $b->[1], 0) = ']'; substr($str, $b->[0], 0) = '['; } return $str; }

Comment on Answer: How do I put bracket on substring(s) of a string?
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (11)
As of 2014-09-02 20:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (29 votes), past polls