我正在尝试使用XRegExp根据以下标准测试字符串是否为有效单词:
- 字符串以一个或多个 Unicode 字母开头,后跟
- 撇号 (
'
) 后跟一个或多个 Unicode 字母,重复 0 次或多次。 - 字符串在匹配的模式之后立即结束。
也就是说,它将匹配这些术语
Hello can't Alah'u'u'v'oo O'reilly
但不是这些
eatin' 'sup 'til
我正在尝试这种模式,
^(\\p{L})+('(\\p{L})+)*$
但它不会匹配任何包含撇号的单词。我做错了什么?
编辑:使用正则表达式的代码
var separateWords = function(text) {
var word = XRegExp("(\\p{L})+('(\\p{L})+)*$");
var splits = [];
for (var i = 0; i < text.length; i++) {
var item = text[i];
while (i + 1 < text.length && word.test(item + text[i + 1])) {
item += text[i + 1];
i++;
}
splits.push(item);
}
return splits;
};
最佳答案
我认为您需要省略 string start/end anchors匹配单个单词:
"(\\p{L})+('(\\p{L})+)*"
此外,我不确定这些捕获组的用途(这可能取决于您的应用程序),但您可以将它们缩短为
"\\p{L}+('\\p{L}+)*"
关于javascript - 正则表达式不会按预期匹配单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11836493/