C++ 如何使用正则表达式验证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()方法可能会给出错误的输出。