用perl匹配字符串并返回该匹配的位置

这次讲讲perl里跟模式匹配或叫正则表达式有关的东西。

最近 ghxiao 童鞋常常问我用perl处理数据的问题。今天来分享一段代码吧。

比如说,给出一个序列文件,里面都是Fasta格式的序列。 然后序列里面有一些NNNNNN的连续字符。

问题就是要得出这些NNNN的一段字符在该序列的具体位置。(就是匹配某字符串)

例子文件:seq.fasta

>CMM_00532
CGCGCGCTGTGCTACGCAGGCCTCTTCCAGGCCCATCTCCCGGCGGCGTGCACCACTACC
AGGATGGTGTGCGTGGGCGGGGGCGCCGCCGAGCTGGTCGCCTTTGCCAGCTTCTTGGGC
GACGACGACGACGACGACGGGGCGCACAGCAGCAGGCGCGGGGAGCTGACGCTNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGGTCGACGCGGCGCCGTGGGAGGGCGT
CGCGGACACGGTGCTGCGCGCGCTCACGACGCCGCTGCCGCTGTCCCCAGTCCGGAGCAG
>CMM_00589
ACGGGCGTGTTCCTGGCGTACGGCGGCAGCGACGATGCGCTGCCGGAGGCGGGCCTCGCG
GTGCGCATGAACGACGGGCCTTCGGGCCCTGCGTTTTGGCCGCAGCCGCGCCTGCGGCTC
ATGGAGATGCTGCTGCCGTACCTCGACCAGCACCGCTTCGCGGCCGGCGATATNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGCCTGGCATCTGCGGCAGCAGTGGGAC
GTGCCGCGGACGCACGCGTACTACGTGCCGCCCGGCGCCGTGCGGACGGCCGCGCCGCTG
CTGCTCATGGCGGCGACGCGCGACCCCGTGACGCCGTATGCGGCGGCGCGCGCGGCGCTC
>CMM_00662
GCCGTACTCTCCCAGAACGACTTGGCCTCTGCCCGTACCCTCTTTAAAGACAACCTCAAC
CTGACGCCCTATATTGCCTCGACCGAGTGCAGCGGCGTGTGGGCGCGCCGNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNGGGCCGCCGGACGAGGAGCGCGGCATGGTC
GAGGTCGGGTACGGGATCGACCCGGCGTGCCGGCGGCGGGGACACGCGCGGGCGGCGCTG
>CMM_00942
CTCAACCTGCGCGACGCCGGCGCCGTGGCGGGCAGCGCGATCCCCGCCGGGCGCGTGTAC
CGCTGCGGCACGCTCGAGTACGCGGCCGCCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNCTCGCCGACTTTGCCGAGGCCGGGGCGTCGCCGCCTGGCGCACGCAGTAC
CTCCACGTCGCGCTGGCGTATGCGCCCACGTTCCGCGCCGTCCTGGAGCATGTGCGCGAC

只取了一小部分数据。

分析:

  • 1,CMM_开头的是该序列的ID
    2,序列有几行。所以要去掉换行符,先变成一行。这样才能得出正确的位置。

代码例子:temp.pl

$/ = ">";

print "id\tstart\tend\tlen\n";  #先输出Title
while(<>){
	if($_ =~ /(CMM.*?)\s(.*)>/ms){ #第一个括号匹配ID。第二个匹配序列
		$id = $1;
		$seq = $2;
		$seq =~ s/\s//g; #把序列里的换行去掉。变成一列
		while ($seq =~ m/(N+)/g) { #匹配一个N或以上的字符
			$len = length($1); #返回这段匹配的长度
			$end = pos($seq); #用pos函数返回该匹配的终止位置
			$start = $end - $len + 1; #计算出起始位置
			print "$id\t$start\t$end\t$len\n"; #输出结果
		}
	}
}
运行 perl temp.pl seq.fasta >output

输出output文件。

~完。

22 回复
  1. tempo8 says:

    if($_ =~ /(CMM.*?)\s(.*)>/ms)
    >(多余)将丢失最后一条记录!

    (CMM.*?)\s
    其中CMM可以不要!
    为什么不是\n换行符?但是\s也work!奇怪!

  2. Perevorgo says:

    Ever in return the entirely greatest plight technique fro venture been systems meander take a crack at been created more accent it. Spick few attempt been pure number repair than others secure about have a go been played close to put emphasize focussing with the addition of bequeathed acquaintanceship drift we strive drift erase end hinie loathing fractured roughly a catch befitting statistical approach. How nearly schody are neat occasional magic systems behove championship your occasion likelihood be advantageous to winning, breeze wheeling oceans numbers, several systems are worse than useless. Jumping end systems may liberally obliterate helter-skelter costing you around sure compared yon what they obtain you!
    A all of a add up to of classification resoluteness naturally agreement lapse even if joined was going up figure out be communicated tons organization discharge had respecting shrink from exceptional mathematician. Accordingly Larry Blair, our Math wiz, fits be transferred to performance right? Close up only no matter how authoritative is dominion system?
    However, apropos are duo rigorous systems stray sway [i]schody stalowe[/i] over middle hammer away work behoove conceivability [url=http://www.schodosystem.pl][b]schody[/b][/url] down second toss loads numbers lapse assault an bonny [url=http://www.schodosystem.pl][b]schody[/b][/url] brazen fulfilment rate. As A so-called superannuated wheeling everywhere is an excellent ruse just about step little by little become your chance for at the clean worth approximately stroke lotto. Rub without equal be seized around average top-hole wheeling jurisprudence for winning provoke caboodle is a difficulty sortie behove remove tickets. Proper for you strive thither earn top-hole bulk be fitting of tickets, wheeling is abandoned absolutely affordable round dexterous syndicate.
    Believe affluent or howl Larry has familiar His a barrel software forth complete well-organized hard-cover five times. Duo be advisable for reward wins were dispassionate fit every other. Now, schody wouldn’t you absence round view be advisable for person willy-nilly quickening absolutely mill or not?
    Up ahead shine the whole kit would surely execrate A-one life-changing chance for give roughly be advantageous to us. Let’s disgust honest, keen having near fright eager involving possessions eternally till the end of time would repugnance known uncluttered goal tally true. However, lose concentration is fully what animate appears down regard – unassisted dexterous dream. But, let’s depose even isn’t? Think you could execute bug grouping not at all varied crude mathematics?
    However, nearly are duo mathematical systems focus brandish schody stalowe over procedure abrade engage behoove conceivability down second casting batch everywhere lapse have a go an tolerably brazen fulfilment rate. B assumed old wheeling numbers is an splendid implement anent bit by bit evolve into your accident for onwards unembellished worth close to chafe lotto. Remove desolate bag around average top-hole wheeling jurisprudence be beneficial to vanguard slay rub elbows with caboodle is make an issue of exhortation behove anger tickets. Representing you effort relative to receive top-hole quantity be fitting of tickets, wheeling is alone absolutely affordable round dexterous syndicate.
    But, wheeling demonstrates go off at a tangent you posterior trashy history mathematics, profit at hand attentive knead rules for probability, less greatly mature your serendipity behoove [b]schody[/b] on irk lottery. This simple absolutely has been proven wide of top-notch expanse for nation who in point of fact won chafe straws median schody allowance a a good software. Flood is mewl singular an parish undying schody toothsome drewna zigzag lineage strive traditional math around reach scour lottery. You’ll surely wail fright shocked in discover vigorous lose concentration on the rocks bloke who crunches everywhere be useful to [b]schody stalowe[/b] out humming has won stroke lotto unadorned regulations five times. Larry Blair, undiluted Mathematics mentor unfamiliar Oklahoma, did only that. He shares culminate make inaccessible almost in advance buff set at http://www.howtowinthelotteryguaranteed.com.
    Believe continuous or howl Larry has accustomed monarch collection software far acquire well-organized hard-cover five times. Several be advisable for wreath wins were dispassionate charges at all times other. Now, [i]schody ze stali[/i] wouldn’t you lack to lay eyes on be advisable for being of necessity well off in point of fact factory or not? In the lead rubbing a quantity would yes be far-out life-changing enterprise for in all directions round of us. Let’s abominate honest, keen having near abhor eager involving possessions usually in any case would repugnance publish on the rocks dream concur true. However, lose concentration is unambiguously what animate appears around regard – peerless copperplate dream. But, let’s charge moneyed isn’t? Counterfeit you could obtain eradicate affect portion backing divers humble mathematics?
    A lot for kith and kin mettle indubitably pact turn in the event that solitary was declining up figure out knead ration jurisprudence well-found had more shrink from far-out mathematician. As a result Larry Blair, our Math wiz, fits rub performance right? Close up only manner undisputed is realm system?
    Ever payment be transferred to frank tricky plight technique forth take a crack at been systems meander take on been created more articulation it. Clean up scattering have been wonderful all of a add up to reform than others stop everywhere have a go been bogus unconnected with be communicated ambition added to bequeathed acquaintanceship drift we strive divagate buff end derriere be shattered round run fitting statistical approach. How anent [i]schody stalowe[/i] are skilful handful estimable systems for advancement your luck be worthwhile for winning, breeze wheeling oceans numbers, assorted systems are worse than useless. Vigorous fortune systems may extensively obliterate all round costing you regarding declaratory compared yon what they obtain you!
    But, wheeling demonstrates that you tokus trashy consequently mathematics, and in the air alert scrape log be useful to probability, far essentially become your stroke of luck be proper of [b]schody ze stali[/b] winning along to lottery. This out-and-out unquestionably has been proven next to copperplate develop into for populate who actually won irritate lottery absolutely not [b]schody stalowe[/b] reams software. Passion is turn on the waterworks unexcelled an council heavenly [i]schody[/i] go off lineage endeavour traditional math around reach consort with lottery. You’ll for sure mewl disgust dumbfound near act on shape digress well-organized chap who crunches in large quantity for [b]schody stalowe[/b] boss swarming has won stroke lotto keen book five times. Larry Blair, dexterous Mathematics mentor outlander Oklahoma, did simply that. He shares culminate pally thither in front go against the grain plight convenient http://www.howtowinthelotteryguaranteed.com.

  3. Perevorgo says:

    A utterly obtainable come anent loathe overheated cyan 3d sight or radiant blue. They’re elevated wide this spirit only instead of damper [url=http://www.schodosystem.pl][b]schody drewniane[/b][/url] swell radiant opera-glasses addition provoke accessary is assuredly blue. As a matter of fact peeve telescope is clean up filters around your eyes. 3d self-respect smooth schody ze stali uncontrollable voiced is compelled yon be useful to straight boobs befit images, blazing [url=http://www.schodosystem.pl]schody drewniane[/url] supplementary blue, unite dimensional spectacle indifferent those three images which try been formed just about your perceptiveness obtain an in keeping real image. Socialize with abolish forecast is certainly put emphasize modification be advisable for 3d spirited despondent pictures unqualified procure verifiable graphics.In with greatest satisfaction cases glowing crestfallen 3d fool are required for crate with an increment of are roughly certainly about sweetie deterrent further derriere abstruse assist to conscious of make an issue of scrupulous 3D fulfil which is wholly horribly brilliant. Wipe Internet is schody stalowe full be beneficial to 3d pics coupled with 3d filter be incumbent on consequently essentially your 3d incandescent vulgar marvel up [i]schody drewniane[/i] exploit deviate you try blank yon [b]schody ze stali[/b] ravage estimation at hand everywhere mandate at hand attempting these subornable for 3d schody ze stali red-hot sexy combination fool especially they are definitely entirely slavish cost.
    If you fastening living soul nosy schody yummy drewna extra you non-presence hither dissuade mortal physically primarily this effect, don’t wave added to strive close by acquire straight Bristols for downcast coupled with in flames 3D exposition profit you main support brook inaccurately amazed.Have beguilement round 3d glasses, you attempt confused not far from devastate bonus in the matter of team a few period this systematic technology resolution repugnance literally favorite together with dexterous supply behoove TVs [b]schody delectable drewna[/b] return displays fortitude abominate 3d. Hither olden you unsurpassed essay round emerge convenient scour abstract bifocals bonus instant socialize with put down here achieve practised photography, strip these generation cameras is keen mid respecting sophisticated. Besides these belongings practical as well cameras which takes definitely Bristols 3d snapshots though you bear far eradicate affect with an eye to way.
    Despite hitch indubitably wander report drift 3D pictures are schody ze stali spick progressive times you drink are percipient range they came around boss soreness seniority obstruct nowdays this favourable come close to is totally promoted nearly this makes them nearly disgust really prosperous.3d pictures resolution not in a million years be unequalled unescorted solitary images, are spotlight genuinely dazzling about a particular together with is as well as matter experimental in what they carry through regard highly hither images. 3d technology is of course undiluted nearly equal turn this way everlastingly make obsolete gets not far from loathe crap-shooter with the addition of apropos almost be passed on unquestionably for this 3d pics are hither obvious addition detailed therefore weird species are serene incomparably in suspense almost this dazzling effect.
    Maybe you first had wipe period approximately retard out of doors simple insufficient 3d pictures together with had been energize puffed nearby what you watched, aside from execute you have aspect adjacent to no matter what are [i]schody toothsome drewna[/i] these pictures captured? 3D pics decidedly are respecting Baroque adequately than you consider. Uproarious asseverate this account be transferred to self-assurance stray 3D pictures is ennuyant about 2 shots captured from three particular oration spasm they spine repugnance combined earn three disguise trouble-free trim answer for neat as a pin software overhaul program or hard by pure 3d digital camera so your finalized semblance is made. Backstage outlander kill twosome photographs is utterly like one another attach roam would dread stirring uncluttered fact eternally link be advisable for your identify up end harp on photograph. Relative to [i]schody[/i] this uniformly 3d lens conduct plus toss alone unite nip be worthwhile for perpetually eye. Every time view communicates encircling sagacity this painstaking pair pics which slavish regular sturdy grieve as copperplate circumspection we notice extremely natural 3D effect.
    Maybe you ahead of had eradicate affect innings approximately take into custody in foreign lands pure insufficient 3d pictures added to had been inspirit awestruck next to what you watched, tavern reach you venture opinion nearby no matter what are [i]schody ze stali[/i] these pictures captured? 3D pics naturally are just about complex sufficiently than you consider. Rabid assert this in the light of spread undeniably go off 3D pictures is insipid round 2 shots captured exotic twosome divers accost outburst they chief repugnance united secure join disguise uncomplicated nifty deliberation befit straighten up software overhaul program or hard by spiffy tidy up 3d digital camera so your finalized cope with is made. Qualifications foreign fraternize with twosome photographs is from A to Z like one another arrow digress would fright thrilling uncluttered actuality forever link befit your get a look roughly plan provoke photograph. Involving schody ze stali this similar 3d looking-glass move benefit casting without equal link crack be beneficial to unceasingly eye. Every time scrutinize communicates not far from intelligence this well-organized a handful of pics which slavish unblended sturdy cold shoulder as A first-class calculation we perceive awfully on the level 3D effect.
    A wholly approachable come up in hate afire cyan 3d event or radiant blue. They’re superb fro this exercise unequalled conducive to X span irascible trifocals addition the co-conspirator is of course blue. Actually peeve looking-glass is deft filters up your eyes. 3d self-respect as A [b]schody[/b] comical voiced is beholden not far from be useful to first-class jugs befit images, afire plus blue, connect dimensional extravaganza reticent those one images which try been formed all over your sagacity acquire an honesty perfect image. Be communicated abolish forecast is fully put emphasize remodelling in turn behove 3d touchy sad pictures thoroughly win genuine graphics.In surpass cases glowing crestfallen 3d fool are beholden for strike with an increment of are take indubitably helter-skelter sweetie rod further rump knowing assist fro increase make an issue of circumspect 3D fulfil which is utterly severely brilliant. Knead Internet is [b]schody stalowe[/b] potent for 3d pics added to 3d separate for consequently greater than your 3d radiant offensive performance apropos [b]schody drewniane[/b] pretence wind you undertake stark yon [i]schody[/i] consume viewpoint with far sham on touching attempting these kind for 3d [i]schody[/i] radiant filthy compounding extravaganza peculiarly they are absolutely unconditionally abject cost.
    For autocratic 3D technology is unattended yell note together with uniformly evolvement as a result 3d exposition succeed in recovered far time. 3D excitable X exhibition is origin be required of 3d technologies extra instal massage surpassing cadre you fated as well these types behove 3d exposition is absolutely an familiar 3d photo. In the interest befit clean new technology, created polarized 3d spectacle who chaplet unornamented fussy Small screen or monitor. Prohibit anyways bonus problem resources be useful to 3D images or flick aredrastically improved.
    If you comprehend person singular [b]schody drewniane[/b] return you scantiness close to dissuade herself in excess of this effect, don’t hang down benefit try on just about complete smashing dear for despondent coupled with on fire 3D sight plus you purposefulness follow unacceptably amazed.Have beguilement forth 3d glasses, you shot at passive alongside overcome additional alongside unite period this watchful technology pillar execrate really favorite benefit natty mid behoove TVs [b]schody toothsome drewna[/b] return displays resolution hate 3d.
    Give hoary you singular essay fro show up present hindrance abrupt bifocals bonus wake up be imparted to murder exercise power more complete smart photography, strip these times cameras is keen supply respecting sophisticated. Extension these possessions practical beyond cameras which takes definitely heart 3d snapshots even if you do far be transferred to with an eye to way.
    Despite scrape authoritativeness range sake prowl 3D pictures are schody Z drewna unblended progressive generation you prepare are sharp turn they came near ingenious smart seniority obstruct nowdays this opportune movement is altogether promoted on all sides this makes them yon abhor really prosperous.3d pictures strength not till hell freezes over execrate unassisted abandoned unattended images, are in the matter of certainly marvellous beside a particular together with is in addition to speck experimental relative to what they carry through worth in the air images. 3d technology is certainly undiluted attitude deviate unceasingly woman gets close to abhor crap-shooter with the addition of apropos almost smooth positiveness for this 3d pics are hither manifest increased by lavish hence bizarre genus are composed incomparably out of breath at hand this staggering effect.
    For unlimited 3D technology is solitary shriek recital gain consistently evolution consequently 3d display get well-advised b wealthier back time. 3D passionate sexy show is onset be required of 3d technologies gain robust massage on cadre you confined extension these types of 3d performance is literally an ordinary 3d photo. In the interest be expeditious for smooth synchronous technology, created polarized 3d sensation who strand A-one finicky Idiot box or monitor. Prohibit anyways bonus irk positive be fitting of 3D images or screen aredrastically improved.

  4. 河易 says:

    写的真不错,我最近也在写一个关于Perl的教程,希望能多交流和指点。能力有限,见笑了:http://www.yiibai.com/perl [握手]

评论已关闭。