develooper Front page | | Postings from June 2007

regexp quickie

Thread Next
Phil Carmody
June 27, 2007 05:46
regexp quickie
Message ID:
Say I had a string satisfying /^[A-Z_]{6}$/, but not equal to '______' and I
wish to extract from that the 1 or 2 letters which are closest to the n-th
character in the string. Is there a simple regexp to perform that task?

if the string=A_Z_K_ then:
if n=1, then I want 'A' (or 'AA', not fussed)
if n=2, then I want 'AZ'
if n=3, then I want 'Z' (or 'ZZ', not fussed)
if n=4, then I want 'ZK'
if n=5 or 6, then I want 'K' (or 'KK', not fussed)

I can see how to do it with the concatenation of two matches from two substrs,
but that's barely simpler than a naive loop over each character forwards and


()  ASCII ribbon campaign      ()    Hopeless ribbon campaign
/\    against HTML mail        /\  against gratuitous bloodshed

[stolen with permission from Daniel B. Cristofani]

Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games.  

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About