javascript - 如何限制正则表达式中的字符范围?

标签 javascript node.js regex

可以说,

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/

    相关文章:

    javascript - jQuery - 返回 $(this) DOM 元素

    javascript - Bootstrap 对齐

    node.js - 卸载npm仍然在ubuntu16.04ls中运行node-red

    c# - 占位符和正则表达式

    java - 用于sql分析的正则表达式

    javascript - 使用 Fetch 返回 GitHub 用户数据

    javascript - d3js 可重用图表组件和转换

    javascript - 使用 json 对象在 map 上添加多个标记

    node.js - mongodb + nodejs 保存聊天记录

    regex - 如何从正则表达式搜索中排除逗号?