C++ 使用正则表达式验证UPI ID
在这个问题中,我们将使用正则表达式来验证UPI ID。UPI是统一支付接口,每个客户都会被分配一个UPI ID,其他人可以使用它来向您转账。
- UPI ID只能包含字母和数字字符。
-
UPI ID应该始终包含一个’@’字符。
-
UPI ID不应该包含空格。
-
UPI ID可以包含一个句点(.)或连字符(-)。
问题描述 − 我们已经给定了一个字符串格式的UPI ID。我们需要使用正则表达式来验证UPI ID。
示例示例
输入
upi = "shubham@okaxis"
输出
‘Yes’
解释
UPI id包含’@’和字母数字字符。因此,它是有效的。
输入
upi = "shubhamokaxis";
输出
No
解释
UPI ID不包含“@”字符。因此,它不是一个有效的UPI ID。
输入
upi = "shubham@:okaxis";
输出
No
解释
UPI id包含‘:’,这不是一个有效的字符。
正则表达式
正则表达式是一个用于识别字符串中的模式的字符串。这是用于验证UPI的正则表达式。
"^[0-9A-Za-z.-]{2,256}@[A-Za-z]{2,64}$"
- ^ – 正则表达式的开头。
-
[0-9A-Za-z.-]{2,256} – 开头应包含2到256个字母数字、句点或连字符字符。
-
@ – 必须包含@字符。
-
[A-Za-z]{2,64} – 在“@”字符后面,应包含2到64个字母字符。
第一种方法
在这种方法中,我们将使用“regex_match”方法来验证正则表达式。
算法
- 步骤1 - 导入“regex”库以使用与正则表达式相关的方法。
-
步骤2 - 使用“regex”数据类型创建名为“upiPatt”的正则表达式。
-
步骤3 - 使用empty()方法检查字符串是否为空。如果是,则返回false。
-
步骤4 - 使用“regex_match()”方法,并将UPI字符串作为第一个参数,正则表达式作为第二个参数。如果该方法返回true,则从函数中返回true。否则,返回false。
示例
#include <bits/stdc++.h>
#include <regex>
using namespace std;
bool validateUPI(string upi) {
// Defining the regular expression
const regex upiPatt("^[0-9A-Za-z.-]{2,256}@[A-Za-z]{2,64}$");
// Handling the empty string
if (upi.empty()) {
return false;
}
// Matching the UPI and regular expression
if (regex_match(upi, upiPatt)) {
return true;
} else {
return false;
}
}
int main() {
string upi = "shubham@okaxis";
if (validateUPI(upi)) {
cout << "Yes, it is a valid UPI ID!";
} else {
cout << "No, it is not a valid UPI ID!";
}
return 0;
}
输出
Yes, it is a valid UPI ID!
时间复杂度 – 匹配模式的O(N)。
空间复杂度 – O(1),因为我们不使用任何动态空间。
方法2
在这个方法中,我们将使用regex_search()方法来使用正则表达式验证UPI id。
算法
- 步骤1 - 使用’regex’数据类型创建正则表达式。
-
步骤2 - 如果字符串为空,则返回false。
-
步骤3 - 将UPI和正则表达式作为regex_search()方法的参数来验证UPI id。
-
步骤4 - 根据regex_search()方法的返回值返回true或者false。
示例
#include <bits/stdc++.h>
#include <regex>
using namespace std;
bool checkforUPI(string upi) {
// Defining the regular expression
const regex upiPatt("^[0-9A-Za-z.-]{2,256}@[A-Za-z]{2,64}$");
// For empty strings
if (upi == "") {
return false;
}
// Using the regex_search() method
if (regex_search(upi, upiPatt)) {
return true;
} else {
return false;
}
}
int main() {
string upi = "abcd@oksbi";
if (checkforUPI(upi)) {
cout << "Yes, it is a valid UPI ID!";
} else {
cout << "No, it is not a valid UPI ID!";
}
return 0;
}
输出
Yes, it is a valid UPI ID!
时间复杂度 – 验证 UPI id 的时间复杂度为 O(N)。
空间复杂度 – O(1)
regex_search() 和 regex_match() 方法都用于使用正则表达式验证字符串,但两者在匹配行为方面存在一些细微差异。程序员可以使用任何方法来使用正则表达式验证 UPI id。