【问题标题】:Js Regex only allowed characters one occurenceJs Regex 只允许字符出现一次
【发布时间】:2022-01-24 17:22:45
【问题描述】:

非常努力地尝试正则表达式,但无法获得所需的结果。

  1. 必须以数字开头,最多 4 个
  2. 后面只有一个允许的字母

请看下面的代码。

var strings = [
 '1h', //should match
 '13s', //should match
 '30m', //should match
 '42hr', //should not match
 '8   hours  ', //should not match
 '765765', //should not match
 '5sec', //should not match
 '23445345345s', //should not match
 '335m' //should match
];

for (var i = 0; i < strings.length; i++) 
{
    var match = strings[i].match(/\d{4}[h|m|s]{1}/g);
  console.log(strings[i], (match ? "Match" : "Not match"));
}

【问题讨论】:

  • "必须以数字开头,最多为 4":那么你需要{1,4},而不仅仅是{4}。对于字符组,不要使用|,所以使用[hms]
  • @AndrewMorton 试过了。 5sec 和 23445345345s 不应匹配。但它正在匹配。
  • 糟糕,我的意思是请查看 regex101.com/r/lMlyFS/1 以查看 /^[0-9]{1,4}[hms]$/gm 是否有效。

标签: javascript node.js regex


【解决方案1】:

我添加了一个 ^ 来匹配从头开始

strings.filter(x =>  x.match(/^\d{1,4}[hms](?!\w)/g)  )

【讨论】:

    【解决方案2】:

    你的正则表达式应该是:

    /^\d{1,4}[hms]$/gm
    

    首先,d{4} 需要 4 位数字

    d{1,4}改成一到四位数

    然后添加一个$来表示字符串的结尾,所以它不允许在字母后面有更多字符

    查看Regex101,对测试和理解正则表达式非常有用

    【讨论】:

    • 嘿 23445345345s 正在匹配中
    • 一开始忘了^,修复了
    • 使用字符类来匹配 h m s 不需要管道字符。模式可以写成^\d{1,4}[hms]$
    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    相关资源
    最近更新 更多