Friday, 15 February 2013

postal code - Regex to match the first half of a UK postcode -



postal code - Regex to match the first half of a UK postcode -

i need regex match first half of uk postcode, , it's possible 1 half or total post code passed in.

there great way match total postcode here: uk postcode regex (comprehensive)

however need first 3 or 4 characters of postcode, possibility of half post code or postcode without spaces getting passed in, of these:

sl4 4bz sl44bz - pull out 'sl4' sl4 dy10 dy10 3bd dy10 3bd

the regex needs match:

if it's 5 characters long (excluding spaces), remove lastly 3 characters , first 2 remaining characters half-a-postcode if it's 6 characters long (excluding spaces), remove lastly 3 characters , first 3 remaining characters half-a-postcode if it's 7 characters long (excluding spaces), remove lastly 3 characters , first 4 remaining characters half-a-postcode if it's 2, 3 or 4 characters long, maintain it

but can't quite head around how write complex.

updated 2/5 characters well, total coverage = 2/5 or 3/6 or 4/7

this works input samples. here 2 variations of same thing.

results in capture grouping 1

# (?m)^([a-z0-9]{2,4})(?:\s*[a-z0-9]{3})?$ (?m) ^ ( # (1 start) [a-z0-9]{2,4} ) # (1 end) (?: \s* [a-z0-9]{3} )? $

results in capture grouping 0

# (?m)^[a-z0-9]{2,4}(?=(?:\s*[a-z0-9]{3})?$) (?m) ^ [a-z0-9]{2,4} (?= (?: \s* [a-z0-9]{3} )? $ )

@smickie - update - regarding question inline-modifiers in js. (i'm not js expert here simple example) don't believe inline modifiers build available. however, can added via flags parameter (enum) or in /../flags notation.

you can see illustration work in jsfiddle here --> http://jsfiddle.net/cdcv8uug/

var teststr = "sl\nsl 4bz\nsl4bz\nsl4\nsl4 4bz\nsl44bz\ndy10\ndy10 3bd\ndy10 3bd"; var arr = teststr.match( /^[a-z0-9]{2,4}(?=(?:\s*[a-z0-9]{3})?$)/mg ); var res = "using match() -> capture grouping 0\nteststr.match(/^[a-z0-9]{2,4}(?=(?:\s*[a-z0-9]{3})?$)/mg)\n"; (var index = 0; index < arr.length; index++) { res += index + ": " + arr[index] + "\n"; } var re = /^([a-z0-9]{2,4})(?:\s*[a-z0-9]{3})?$/mg; res += "\nusing exec() -> capture grouping 1\nvar re = /^([a-z0-9]{2,4})(?:\s*[a-z0-9]{3})?$/mg;\nre.exec(teststr)\n"; index = 0; while ((arr = re.exec(teststr)) != null) { res += index + ": " + arr[1] + "\n"; index++; } alert( res );

regex postal-code

No comments:

Post a Comment