可以说,
let sentence= "Dear user {#val#}{#val#} thanks"
{#val#} 是上句中的动态值。这里可以代替 {#val#},但可以有任何值,但至少可以有 0 个字符,最多可以有 5 个字符。所以我将 {#val#} 替换为 .{0,5} 。除了 {#val#} 部分之外,我不需要考虑空格,所以我形成的正则表达式是,let regex = /^Dear\s*user\s*.{0,5}.{0,5} thanks$/i
let customermsg = "Dear user 1 2 thanks" //Should be valid
let customermsg1 = "Dear user 12345 6789 thanks" //Should be valid
let customermsg2 = "Dear user 123 5 6789 thanks" //Should be valid because space can also be considered as a character and for fist .{0,5} => 123 5 and for second .{0,5} => 6789
let customermsg3 = "Dear user 1 thanks" //Should pass
let customermsg4 = "Dea r user 1 tha nks" // Should Pass since spaces are not considered in the static portion.
但是当我尝试使用下面的测试时, regex.test(customermsg)
它完全相反。即使我尝试过以下方法,let splitters=/{\\#val\\#}|((\\s\*))/gi;
sentence = sentence.replace(splitters, (x, y) => y ? y : ".(\\S{0,5})");
这将正则表达式返回为, /^Dear\s*user\s*.(\S{0,5}).(\S{0,5})\s*thanks$/
但这也没有按预期工作。我坚持这一点。请帮我。
最佳答案
您需要根据以下内容检查数字和空格是否多次出现
"Dear user 1 thanks" //Should fail since only one value is there
因此,您的正则表达式很好,只是它不检查数字和空格是否存在多次。
使用以下正则表达式
Dear\s*user\s*([\d]+[\s]+){2,5}\s*thanks$
([\d]+[\s]+){2,5}\s*
([\d]+[\s]+){2,5}\s*
部分确保一个数字至少出现两次,因此字符串中的单个数字 Dear user ... thanks
将失败。您可以在数字之前、之间和之后使用任意数量的空格。
let regex = /Dear\s*user\s*([\d]+[\s]+){2,5}\s*thanks$/i
let customermsg = "Dear user 1 2 thanks" //Should be valid
let customermsg1 = "Dear user 12345 6789 thanks" //Should be valid
let customermsg2 = "Dear user 123 5 6789 thanks" //Should be valid because space can also be considered as a character and for fist .{1,5} => 123 5 and for second .{1,5} => 6789
let customermsg3 = "Dear user 1 thanks" //Should fail since only one value is there
let customermsg4 = "Dear user 435 4523 thanks" // With many spaces
console.log(regex.test(customermsg));
console.log(regex.test(customermsg1));
console.log(regex.test(customermsg2));
console.log(regex.test(customermsg3));
console.log(regex.test(customermsg4));
关于javascript - 如何限制正则表达式中的字符范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66348940/