我目前正尝试使用以下代码验证文本框中的字符串:
$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);
})
}
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]
不起作用。
答案 0 :(得分:1)
更改为:
(?<serverNumber>\d+)
不是捕获组的有效JavaScript regexp语法。 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];
请注意,alarmId
和serverId
将是上述字符串之后的字符串。如果您想将它们转换为数字,那么提取的字符串"012"
和"12"
将被视为相同,请添加parseInt
:
var alarmNumber = parseInt(matches[1], 10);
var serverNumber = parseInt(matches[2], 10);