Reputation: 16959
Using XRegExp I have the following regex to match words that start with uppercase letters:
var regex = XRegExp("/\p{Ll}*\p{Lu}+\p{Ll}*/gu");
var matches = XRegExp.exec("TestString", regex);
However the matches variable is always null. I am not sure if the regex is wrong or if I am using xregexp incorrectly. How can I get matches for words that start with uppercase letters?
Upvotes: 1
Views: 358
Reputation: 627022
You can use XRegExp.match
with the scope
set to all/g
modifer, or run XRegExp.exec
in a loop:
var regex = XRegExp("\\p{Ll}*\\p{Lu}+\\p{Ll}*");
// Or: const regex = XRegExp(String.raw`\p{Ll}*\p{Lu}+\p{Ll}*`);
var matches = XRegExp.match("TestString", regex, "all");
console.log(matches);
var regex1 = XRegExp("\\p{Ll}*\\p{Lu}+\\p{Ll}*", "g");
var results=[], match;
XRegExp.forEach("TestString", regex1, function (match, i) {
results.push(match[0]);
});
console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.2.0/xregexp-all.min.js"></script>
NOTE:
String.raw
notation with single backslashes in the string literalXRegExp
patterns defined with string literalsu
modifier does not make sense here, unless you want to support ES6 regex features like \u{XXXX}
and .
matching any Unicode code pointg
can be overridden with all
as the scope
value.See XRegExp.match(str, regex, [scope])
:
Returns the first matched string, or in global mode, an array containing all matched strings. This is essentially a more convenient re-implementation of
String.prototype.match
that gives the result types you actually want (string instead of exec-style array in match-first mode, and an empty array instead ofnull
when no matches are found in match-all mode). It also lets you override flagg
and ignorelastIndex
, and fixes browser bugs.
And its scope
parameter:
Use 'one' to return the first match as a string. Use 'all' to return an array of all matched strings. If not explicitly specified and regex uses flag
g
, scope isall
.
Upvotes: 2
Reputation: 163437
According to the examples in the documentation, you can double escape the backslash and the flags is the second parameter.
XRegExp(pattern, [flags])
The value of pattern can be {String|RegExp}
so you could use it like this using String
var regex = XRegExp("\\p{Ll}*\\p{Lu}+\\p{Ll}*", "gu");
var matches = XRegExp.match("TestString", regex);
console.log(matches);
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.2.0/xregexp-all.min.js"></script>
Or use it like this using a RegExp
var regex = XRegExp(/\p{Ll}*\p{Lu}+\p{Ll}*/gu);
var matches = XRegExp.match("TestString", regex);
console.log(matches);
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.2.0/xregexp-all.min.js"></script>
Upvotes: 2