简体   繁体   中英

Regular expression to extract first letters of UK postcode

I want to extract the area code from a UK postcode using a regular expression. For example this would be removing "SW" from "SW11 1AW". The area is always the first characters of the string and is always followed by a number. I can't just extract the first two characters as sometimes there is only one letter, eg "E1 4PN". So it needs to match AZ only from the start of the string until it hits a number and return just the letters. For the sake of argument the string will always be upper case.

Thanks.

(假设PHP)

$letters = preg_replace('#^([a-z]+).*#i','$1',$postcode);

In ruby this would look like:

postcode = 'SW11 1AW'
postcode[/^[a-z]+/i] # get the area code
#=> "SW"
postcode[/^[a-z]+(.*)/i,1] # get the rest
#=> "11 1AW"

Note: The i flag (ignore case) is set. So both, uppercase and downcase letters work.

^(?i)[a-z]+(?=\d)

如果有两个或第一个字母,如果只有一个字母在数字之前,将会找到前两个字母,无论情况如何。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM