function findSubstringInString(mainStr, pattern) {
// 使用 match() 查找给定的模式
var result = mainStr.match(pattern);
if (result !== null) {
// 如果找到了匹配项,则返回匹配的结果
return "Match found: " + result[0];
} else {
// 如果没有找到匹配项,则返回相应的消息
return "No match found.";
}
}
// 定义字符串和要查找的模式
var str = "Hello world, welcome to the universe.";
var pattern = /welcome/; // 正则表达式,用于匹配 "welcome"
// 调用函数并打印结果
console.log(findSubstringInString(str, pattern));
match() 方法用于在字符串中搜索与正则表达式相匹配的内容。如果找到了匹配项,match() 方法会返回一个数组,其中包含匹配的结果以及任何捕获的分组;如果没有找到匹配项,则返回 null。
在这个例子中:
// 官方软件群711841924
// 定义 findSubstringInString 函数
function findSubstringInString(mainStr, pattern) {
// 使用 match() 查找给定的模式
var result = mainStr.match(pattern);
if (result !== null) {
// 如果找到了匹配项,则返回匹配的结果
return "Match found: " + result[0];
} else {
// 如果没有找到匹配项,则返回相应的消息
return "No match found.";
}
}
// 定义 validateEmail 函数
function validateEmail(email) {
var pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // 简单的电子邮件验证正则表达式
return findSubstringInString(email, pattern);
}
// 调用 validateEmail 函数并打印结果
console.log(validateEmail("user@example.com")); // 输出: Match found: user@example.com
console.log(validateEmail("invalid-email")); // 输出: No match found.
function extractPhoneNumber(text) {
var pattern = /\d{3}-\d{3}-\d{4}/; // 匹配格式为 xxx-xxx-xxxx 的电话号码
return findSubstringInString(text, pattern);
}
console.log(extractPhoneNumber("Call me at 123-456-7890.")); // 输出: Match found: 123-456-7890
console.log(extractPhoneNumber("No phone number here.")); // 输出: No match found.
// 定义 findSubstringInString 函数
function findSubstringInString(mainStr, pattern) {
// 使用 match() 查找给定的模式
var result = mainStr.match(pattern);
if (result !== null) {
// 如果找到了匹配项,则返回匹配的结果
return "Match found: " + result[0];
} else {
// 如果没有找到匹配项,则返回相应的消息
return "No match found.";
}
}
// 定义 validateURL 函数
function validateURL(url) {
var pattern = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/; // 简单的URL验证正则表达式
return findSubstringInString(url, pattern);
}
// 调用 validateURL 函数并打印结果
console.log(validateURL("https://www.example.com")); // 输出: Match found: https://www.example.com
console.log(validateURL("invalid-url")); // 输出: No match found.
// 定义 findSubstringInString 函数
function findSubstringInString(mainStr, pattern) {
var result = mainStr.match(pattern);
if (result !== null) {
return "Match found: " + result[0];
} else {
return "No match found.";
}
}
// 定义 findErrorInLog 函数
function findErrorInLog(log) {
var pattern = /ERROR: (.+)/; // 匹配以 "ERROR: " 开头的错误信息
return findSubstringInString(log, pattern);
}
// 调用 findErrorInLog 函数并打印结果
console.log(findErrorInLog("INFO: System started. ERROR: Failed to connect to database.")); // 输出: Match found: ERROR: Failed to connect to database.
console.log(findErrorInLog("INFO: System running normally.")); // 输出: No match found.
这些例子展示了如何在不同的实际场景中使用 findSubstringInString
函数来查找和处理字符串中的特定模式。
欢迎光临 B2B网络软件 (http://bbs.niubt.cn/) | Powered by Discuz! X3.2 |