我试图在javascript中应用正则表达式但我收到以下错误Syntax Error: invalid quantifier
(?x)^(?:https?://)?
(?:(?:(?:www\.|m\.)?soundcloud\.com/
(?P<uploader>[\w\d-]+)/
(?!sets/)(?P<title>[\w\d-]+)
)
)
以下是使用相同正则表达式
的示例var regex = '(?x)^(?:https?://)?(?:(?:(?:www\.|m\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/(?!sets/)(?P<title>[\w\d-]+)))';
var url = 'https://soundcloud.com/lordemusic/tennis-court';
var match = url.match(regex);
console.log(match);
根据javascript正则表达式linter,它说Unexpected character "x" after "?"
导致错误的原因是什么?如何更改正则表达式以使其正常工作?此外,如果命名捕获组导致错误,我如何用数字索引替换命名捕获组?
答案 0 :(得分:2)
有几种味道&#39;你的正则表达式的问题。
(?x)
这是一个在JavaScript中有效的近距离转换:
以下是一些JavaScript代码,可帮助您开始检索组的内容(请参阅在线demo)。
<script>
var subject = 'https://soundcloud.com/lordemusic/tennis-court';
var regex = /^(?:https?:\/\/)?(?:(?:(?:www\.|m\.)?soundcloud\.com\/([\w\d-]+)\/(?!sets\/)([\w\d-]+)))/i;
var match = regex.exec(subject);
if (match != null) {
var group1 = match[1];
var group2 = match[2];
document.write(group1, "<br>");
document.write(group2, "<br>");
} else {
result = "";
}
</script>