[英]RegExp Match returning whole word not groups
I'm currently trying to validate strings in a text box with this code: 我目前正在尝试使用以下代码验证文本框中的字符串:
$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);
})
}
The output of test
is this: 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)
I can't seem to access any capture groups. 我似乎无法访问任何捕获组。 Trying test[0]
doesn't work. 尝试test[0]
不起作用。
Changes to make: 进行更改:
(?<serverNumber>\\d+)
is not valid JavaScript regexp syntax for a capturing group. (?<serverNumber>\\d+)
对于捕获组无效的JavaScript regexp语法。 JavaScript only understands anonymous capture groups such as (\\d+)
. JavaScript仅理解匿名捕获组,例如(\\d+)
。 As demonstrated further down, you can give names to matches by storing them in variables after extracting them from the match array with []
. 如下面进一步说明的,您可以使用[]
从匹配数组中提取匹配项,然后将它们存储在变量中,从而为匹配项命名。
It's not necessary to make the code work in this case, but your code will be clearer if you change your regexArray
to contain actual regexes /…/
instead of strings "…"
that will be converted to regexes by .match
. 在这种情况下,不必使代码正常工作,但是如果将regexArray
更改为包含实际的regexes /…/
而不是将通过.match
转换为regexes的字符串"…"
,则代码将更加清晰。
The following code demonstrates successful matches: 以下代码演示了成功的匹配:
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); });
To get specific matches from the matches
array, you can add this code: 要从matches
数组中获取特定的matches
,可以添加以下代码:
var alarmId = matches[1];
var serverId = matches[2];
Note that alarmId
and serverId
will be strings after the above. 请注意, alarmId
和serverId
将是上述字符串之后的字符串。 If you want to convert them to numbers, so that the extracted strings "012"
and "12"
would be treated the same, add parseInt
: 如果要将它们转换为数字,以使提取的字符串"012"
和"12"
被视为相同,请添加parseInt
:
var alarmNumber = parseInt(matches[1], 10);
var serverNumber = parseInt(matches[2], 10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.