【问题标题】:REGEX - Get specific values [closed]REGEX - 获取特定值[关闭]
【发布时间】:2020-05-18 06:42:43
【问题描述】:

我有一个 JavaScript,我希望用户只输入以下 4 个值之一。

PL、PH、M、MH

如何使用 REGEX 进行测试?

【问题讨论】:

  • 为什么要为此使用正则表达式?只需将它们放在一个数组中并使用valid_inputs.includes(input)

标签: javascript regex


【解决方案1】:

Regex 不适合这种简单的任务。最好用值定义数组,并检查输入的值是否在该数组中,即:

let allowedValues = ['PL', 'PH', 'M', 'MH'];
let isInputCorrect = allowedValues.includes(inputtedValue);

尽管如此,正则表达式将是:(?:PL|PH|M|MH)

解释:

(?:...) - 非捕获组

PL|PH|M|MH - 替代 - 匹配列出的值之一。

【讨论】:

  • 谢谢,但 'MH' 似乎没有被抓住
【解决方案2】:

如果这是一个使用正则表达式的练习,那么你真的想使用正则表达式来解决它,你可以这样做:

regex = /^(PL|PH|MH|M)$/

choices = ["PL", "PH", "M", "MH", "other", "invalid", "value"]
index = Math.floor(Math.random() * choices.length)
input = choices[index]
console.log("Testing", '"'+input+'"')

x = input.match(regex) 
if (x) {
  x = x[0]
}

console.log("Output:", x) // << one of the allowed strings, or null

按 [ (>) Run code sn -p ] 多次查看不同的输出值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-02
    • 2020-06-26
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 2015-11-27
    • 2012-05-25
    • 1970-01-01
    相关资源
    最近更新 更多