javascript - 如何在一行中匹配 javascript 中的正则表达式

标签 javascript regex

假设我有这个字符串“code 123”,我想得到“123”。但有时字符串为空或有其他内容,因此我的代码必须查找错误。所以我可以这样写:

var id = null;
var m = str.match(/code (\d+)/);
if (m && m.length > 1) id = m[1];
if (id) {
   ...

所以我的问题是,是否有任何方法可以让它与一行或更简单/干净的代码一起工作。像这样的东西:

var id = str.match(/code (\d+)/)[1];
if (id) {
   ...

但是如果找不到字符串,这会破坏代码。我还可以编写一个函数:

function firstMatch(str, search) {
    var m = str.match(search);
    if (m && m.length > 1) return m[1];
    return null;
}

然后:

var id = firstMatch(str, /code (\d+)/);
if (id) {
   ...

但我不想在我编写的每个代码中都包含此函数。

最佳答案

var id = (str.match(/code (\d+)/) || [false,false])[1]

如果 (str.match(/code (\d+)/) 为空或 null,则默认为 [false,false],使得 [0 ],因此 [1],您要访问的索引,等于 false。然后,

if (id) {
  // will not be executed if [1] == false
}

如果 (str.match(/code (\d+)/) 不为 null 或空,则它将优先,并且 if 语句中的代码将被执行,id 将具有来自 (str.match(/code (\d+)/)

的非空、非空值

关于javascript - 如何在一行中匹配 javascript 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40348050/

相关文章:

javascript - 如何从图像中裁剪多项式形状

javascript - 在滚动视口(viewport)中显示元素

php - 单击链接调用原型(prototype)(javascript)函数?

javascript - 如何检查json格式的数据是否存在?

javascript - 正则表达式匹配第一个 '&' 之前的所有 '?'

javascript - 正则表达式检查路径是相对的还是绝对的

javascript - jQuery - 检查是否选中了任何特定的单选按钮

regex - 如何使正则表达式的一部分成为可选的?

regex - 如何根据时间间隔获取这些错误/不匹配字符串

javascript - Jest 测试中未定义正则表达式