Reputation: 619
*
and ?
are the easiest for non-programmers to understand, with respect to wildcards; in this case, multiple characters and a single character wildcards, respectively.
If I receive a string, where a "?"
could appear in any position of the string (e.g. "sing?" or "spo?ls"), how can I convert the string into a javascript regexp which I then compare against a dictionary list? In the case of "spo?ls"
, I would expect to match "spools", "spoils", etc.
Ditto for use of "*"
. Thanks.
Sorry if I was not clear: When I meant common wildcards, common to other environments, not Javascript: so, yes, "?" equals any single character [a-z] and "" equals one or more characters [a-z]. In the case of "", consider "*sing", which would match "arousing", "carousing", etc. Or, "ba*ed", which would match "baked", "banked", or "balanced".
Upvotes: 0
Views: 121
Reputation: 3446
var string = 'spo?ls';
if (string.indexOf('?') !== -1) string = string.replace('?', '[a-zA-Z]');
if (string.indexOf('*') !== -1) string = string.replace('*', '[a-zA-Z]+');
var dictionary = ['spoils', 'spools', 'spoools', 'fools', 'tools'];
var re = new RegExp('^' + string + '$');
var results = dictionary.filter(function(el) {
return (el.match(re) !== null);
});
console.log(results);
["spoils", "spools"];
Now try with string = 'spo*ls';
console.log(results);
["spoils", "spools", "spoools"];
Upvotes: 0
Reputation: 146500
Roughly:
*
→ .*
(any character, zero or more)?
→ .
(any character, exactly one)You'll also need to ignore case (with the i
flag) and ensure nothing else matches (with anchors), e.g.:
spo?ls
→ /^spo.ls$/i
Whatever, I recommend you learn some basics about regular expressions. The MDN documentation is quite good.
P.S. The .
metacharacter does not match new lines.
Upvotes: 3
Reputation: 338
Pattern tokenpattern = Pattern.compile("string you get");
Matcher matcher = tokenpattern.matcher(content to check);
matcher.find();
Is this the answer to your question?
As i can see the String you get is already the RegularExpression and you just have to use it as one.
Lg Teifun2
Upvotes: -1
Reputation: 227280
In regex the period (.
) is used to match "any character".
So you could "convert" "spo?ls"
to /spo.ls/
.
If you wanted the .
to possibly match 0 characters, you could use /spo.?ls/
. The ?
means "0 or 1 character".
In regex, the *
character means "0 or more", and +
means 1 or more.
So depending on what you were looking for, "spo*ls"
could be converted to /spo.+ls/
or /spo.*ls/
.
Upvotes: 1
Reputation: 239382
That isn't what ?
does. ?
is a quantifier, not a wild card.
If you want to match any single character, you need .
.
In your case, you can replace all instances of ?
with .
, and then pass the string to RegExp
:
pattern = "spo?ls";
// produces /spo.ls/
regex = RegExp(pattern.replace(/\?/g, '.'));
Ditto *
: It's a quantifier, not a wild card. You can do the same for *
, except you'd replace all instances of *
with .*
.
Upvotes: 1