如何使用正则表达式验证ISIN?
在这个问题中,我们将使用正则表达式在 C++ 中验证 ISIN 编号。
ISIN 代表国际证券识别号码。它是一个用于识别股票、金融债券等的唯一代码。ISIN 编号的长度可以是 12 或 14,它提供了对特定物品的国际识别。
让我们了解 ISIN 编号的格式。
国家代码 - 它以两个国家代码字符开头。
标识符 - 它包含国家代码后的 9 个字母数字字符。
校验和 - 它包含一个用于检测 ISIN 编号错误的单个数字。
它可能在国家代码和标识符之后包含连字符 (-)。
问题陈述 - 我们以字符串格式给出了一个 ISIN 编号。我们需要使用正则表达式验证 ISIN 编号。
示例
输入
str1 = "SB0123456A98"
输出
Yes
解释
ISIN 编号有效,因为它遵循 ISIN 代码的所有规则。
输入
str1 = "US-01207199D-8"
输出
Yes
解释
这是一个有效的 ISIN 编号。
输入
str1 = "USerw01207199D8"
输出
No
解释
标识符的长度为 12。因此,这是一个无效的 ISIN 编号。
用户可以使用以下正则表达式来验证 ISIN 编号。
^[A-Z]{2}[-]{0,1}[A-Z0-9]{9}[-]{0,1}[0-9]{1}$
^ - 正则表达式的开头。
[A-Z]{2} - 两个字符的国家代码。
[-]{0,1} - 它可能包含连字符 (-)。
[A-Z0-9]{9} - 长度为 9 的标识符,包含从 A 到 Z 和 0 到 9 的字符。
[0-9]{1} - 最后一位校验和数字。
$ - 正则表达式的结尾。
方法 1
在这种方法中,我们将使用 C++ 的 'regex' 库从字符串创建正则表达式模式,并使用 regex_match() 方法验证 ISIN 编号。
算法
步骤 1 - 定义如上所述的名为 'isinPat' 的正则表达式。
步骤 2 - 如果字符串为空,则打印“无效字符串”。
步骤 3 - 在传递 ISIN 编号字符串作为第一个参数和搜索模式作为第二个参数后,执行 regex_match() 方法。
步骤 4 - 如果 ISIN 字符串有效,则打印“是”。否则,打印“否”。
示例
#include <bits/stdc++.h>
#include <regex>
using namespace std;
void ISINValidation(string isinStr) {
// Define the ReGex pattern for isinStr
const regex isinPat("^[A-Z]{2}[-]{0,1}[A-Z0-9]{9}[-]{0,1}[0-9]{1}$");
// For empty string
if (isinStr.empty()) {
cout << "The ISIN string is empty\n";
}
// Matching the string with regex
if (regex_match(isinStr, isinPat)) {
cout << "The ISIN string " << isinStr << " is valid\n";
} else {
cout << "The ISIN string " << isinStr << " is invalid\n";
}
}
int main() {
string str1 = "SB0123456A98";
ISINValidation(str1);
string str2 = "US-01207199D-8";
ISINValidation(str2);
return 0;
}
输出
The ISIN string SB0123456A98 is valid The ISIN string US-01207199D-8 is valid
时间复杂度 – O(N),与 regex_match() 方法的时间复杂度相同。
空间复杂度 – O(1)
方法 2
此方法使用 regex_search() 方法验证 ISIN 编号。当 regex_search() 方法在字符串中找到模式的第一个匹配项时,它将返回 true。
算法
步骤 1 - 对空字符串返回 false。
步骤 2 - 使用 regex_search() 方法验证 ISIN 字符串。
步骤 3 - 如果 ISIN 字符串有效,则从函数返回 true。否则,返回 false。
示例
#include <bits/stdc++.h>
#include <regex>
using namespace std;
bool ISINValidation(string isinStr) {
// Define the ReGex pattern for isinStr
const regex isinPat("^[A-Z]{2}[-]{0,1}[A-Z0-9]{9}[-]{0,1}\\d$");
// For empty string
if (isinStr == "") {
return false;
}
// Matching the string with regex
if (regex_search(isinStr, isinPat)) {
return false;
} else {
return true;
}
}
int main() {
string str1 = "SB0123456A98";
if (ISINValidation(str1)) {
cout << "The ISIN number " << str1 << " is valid" << endl;
} else {
cout << "The ISIN number " << str1 << " is not valid" << endl;
}
return 0;
}
输出
The ISIN number SB0123456A98 is not valid
时间复杂度 – O(N) 用于在字符串中搜索模式。
空间复杂度 – O(1)
regex_match() 将整个字符串与模式匹配,而 regex_search() 对部分匹配返回 true。因此,在某些情况下,regex_search() 方法可能会给出错误的输出。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP