IBAN的正则表达式允许空白并检查确切长度 [英] Regex for IBAN allowing for white spaces AND checking for exact length

查看:149
本文介绍了IBAN的正则表达式允许空白并检查确切长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查德国IBAN的输入字段.应该允许用户留在空白处 ,并且应该验证输入内容的开头为DE,然后精确到20个字符的数字和字母.

I need to check an input field for a German IBAN. The user should be allowed to leave in white spaces and input should be validated to have a starting DE and then exact 20 characters numbers and letters.

在没有空格的情况下,我尝试了

Without the white space allowance, I tried

^[DE]{2}([0-9a-zA-Z]{20})$

但是我找不到在允许的任何位置添加空白的地方和方法.

but I cannot find where and how I can add "white spaces anywhere allowed.

这应该很简单,但是我根本找不到解决方法.

This should be simple, but I simply cannot find a solution.

感谢帮助!

推荐答案

因为您应该使用正确的工具完成正确的任务:您不应依赖于正则表达式来验证IBAN编号,而应使用IBAN校验和算法来检查整个代码实际上是正确的,从而使任何正则表达式都是多余和多余的. ie :删除所有空格,重新排列代码,转换为整数,然后计算余数,这里最好解释.

Because you should use the right tool for the right task: you should not rely on regexps to validate IBAN numbers, but instead use the IBAN checksum algorithm to check the whole code is actually correct, making any regexp superfluous and redundant. i.e.: remove all spaces, rearrange the code, convert to integers, and compute remainder, here it's best explained.

尽管如此,我还是想回答你的问题,因为它很有趣:

Though, there am I trying to answer your question, for the fun of it:

有关:

^DE([0-9a-zA-Z]\s?){20}$

唯一的区别是每次出现字母数字字符后都允许使用空格(或不允许使用空格).

which only difference is allowing a whitespace (or not) after each occurence of a alphanumeric character.

此处是可视化效果:

edit:用于OP的信息,唯一的区别是来自@ ulugbex-umirov的此正则表达式:(?:\s*[0-9a-zA-Z]\s*)进行前瞻性检查,以了解iso国家/地区代码和校验和之间是否存在空格(仅由数字),我故意不支持.

edit: for the OP's information, the only difference is that this regexp, from @ulugbex-umirov: (?:\s*[0-9a-zA-Z]\s*) does a lookahead check to see if there's a space between the iso country code and the checksum (which only made of numerical digits), which I do not support on purpose.

实际上是为了支持由4个字符组成的IBAN语法,如维基百科页面说:

And actually to support a correct IBAN syntax, which is formed of groups of 4 characters, as the wikipedia page says:

^DE\d{2}\s?([0-9a-zA-Z]{4}\s?){4}[0-9a-zA-Z]{2}$

示例

如果您的UI使用Javascript,则可以使用那个库进行IBAN验证:

If your UI is in Javascript, you can use that library for doing IBAN validation:

<script src="iban.js"></script>
<script>
    // the API is now accessible from the window.IBAN global object
    IBAN.isValid('hello world'); // false
    IBAN.isValid('BE68539007547034'); // true
</script>

因此您知道这是有效的IBAN,可以在数据甚至发送到后端之前对其进行验证.更简单,更轻巧,更优雅……为什么还要做些其他事情?

so you know this is a valid IBAN, and can validate it before the data is ever even sent to the backend. Simpler, lighter and more elegant… Why do something else?

这篇关于IBAN的正则表达式允许空白并检查确切长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆