gpt4 book ai didi

javascript - RegExp 匹配返回整个单词而不是组

转载 作者:行者123 更新时间:2023-12-03 02:07:32 25 4
gpt4 key购买 nike

我目前正在尝试使用以下代码验证文本框中的字符串:

 $scope.regexArray = ["Alarm id (?<serverNumber>\d+) has been received from video server number (?<alarmNumber>\d+).", "Alarm id (?<serverNumber>\d+) has been received from video server number (?<alarmNumber>\d+)."];

$scope.validTextBox = false;
$scope.userInput = "";
$scope.validateExpression = function () {

angular.forEach($scope.regexArray, function (value, key) {

var test = $scope.userInput.match(value);

console.log(test);
})
}

测试的输出是这样的:

["Alarm id 4 has been received from video server number 4", index: 0, input: "Alarm id 4 has been received from video server number 4", groups: undefined]

0: "Alarm id 4 has been received from video server number 4"
groups: undefined
index: 0
input: "Alarm id 4 has been received from video server number 4"
length: 1
__proto__: Array(0)

我似乎无法访问任何捕获组。尝试 test[0] 不起作用。

最佳答案

要进行的更改:

  • (?<serverNumber>\d+)不是捕获组的有效 JavaScript 正则表达式语法。 JavaScript 只理解匿名捕获组,例如 (\d+) 。正如下面进一步演示的,您可以通过使用 [] 从匹配数组中提取匹配项后将它们存储在变量中来为匹配项命名。 .

  • 在这种情况下,没有必要使代码正常工作,但是如果您更改 regexArray ,您的代码会更清晰。包含实际的正则表达式 /…/而不是字符串 "…"它将被 .match 转换为正则表达式.

以下代码演示了成功的匹配:

var regexArray = [
/Alarm id (\d+) has been received from video server number (\d+)./,
/Alarm id (\d+) has been received from video server number (\d+)./
];

var userInput = "Alarm id 1000 has been received from video server number 6.";

regexArray.forEach(function(value) {
var matches = userInput.match(value);
console.log(matches);
});

matches 获取特定匹配项数组,您可以添加以下代码:

var alarmId = matches[1];
var serverId = matches[2];

请注意alarmIdserverId将是上面之后的字符串。如果要将它们转换为数字,则提取出的字符串 "012""12"会受到相同的对待,添加 parseInt :

var alarmNumber = parseInt(matches[1], 10);
var serverNumber = parseInt(matches[2], 10);

关于javascript - RegExp 匹配返回整个单词而不是组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49741841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com