使用 C# 动态正则表达式表示数字范围

发布于 2024-12-08 16:46:41 字数 479 浏览 0 评论 0原文

我正在查看英国邮政编码,并尝试弄清楚如何从数据库 (英国邮政编码的第一部分) 获取数据并使用 c# 为其动态创建正则表达式。例如:

AB44-56

我知道我想要什么作为输出:

AB([4][4-9]|[5][0-6])+

但是,我无法弄清楚如何用逻辑来做到这一点,也许我需要先将字母与数字分开,但我不能这样做使用拆分。

我也有其他组合 - 单一范围:

AB31 would be AB[3][1]+

有些只有字母:

BT would be BT+

有些只有一个字母和 1 或两个数字:

G83 Would be G[8][3]

任何建议或指导将非常适合如何编码。

I'm looking at UK postcodes and trying to work out how I can take data from a database (the first part of a UK postcode) and dynamically create a regexp for them using c#. For example:

AB44-56

I know what I want as an output:

AB([4][4-9]|[5][0-6])+

However, I can't work out how I might be able to do this with logic, perhaps I need to split the Letters from the numbers first, but i can't do that using split.

I have other combinations too - single range:

AB31 would be AB[3][1]+

Some with just letters:

BT would be BT+

Some with a single letter and 1 or two numbers:

G83 Would be G[8][3]

Any suggestions or guidance would be very much appriciated how this may be coded.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜巴黎 2024-12-15 16:46:41

a来自维基百科 英国邮政编码:

这可以概括为:(一个或两个字母)(0 到 0 之间的数字)
99)(零个或一个字母)(空格)(单个数字)(两个字母)

所以

^[A-Z,a-z]{0,2}\d+[A-Z,a-z]?\s\d[A-Z,a-z]{2}$

可能有效。

编辑:此外,如果您试图限制邮政编码以表示那些与数据库中的前缀相同的邮政编码,您可以这样做。

var source = "BTasdfweasdf"; //from the database
var input = "BT1A 1BB"; //from the somewhere else
var regex = Regex.Replace(source, @"(^[A-z,a-z]{0,2})(.*)", @"$1\d+[A-Z,a-z]?\s\d[A-Z,a-z]{2}$");
var match = Regex.Match(input,regex); 

afrom wikipedia UK postal codes :

This can be generalised as: (one or two letters)(number between 0 and
99)(zero or one letter)(space)(single digit)(two letters)

so

^[A-Z,a-z]{0,2}\d+[A-Z,a-z]?\s\d[A-Z,a-z]{2}$

might work.

EDIT: Also if you are trying to restric the postal codes to say those with the same prefix as the ones in the database you could do this.

var source = "BTasdfweasdf"; //from the database
var input = "BT1A 1BB"; //from the somewhere else
var regex = Regex.Replace(source, @"(^[A-z,a-z]{0,2})(.*)", @"$1\d+[A-Z,a-z]?\s\d[A-Z,a-z]{2}$");
var match = Regex.Match(input,regex); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文