I have a part of the word and I should find full word in the string using regular expressions. For example, I have the following text:
If it bothers you, call it a "const identifier" instead.
It doesn't matter whether you call max a const variable or a const identififfiieer. What matters...
And the part of the word: identifi
. I have to find both: identifier
and identififfiieer
.
I tried the following regex (javascript):
[\ ,!@#$%^&*()\.\"]*(identifi.*?)[\ ,!@#$%^&*()\d\.\"]
So it searches the part of word surrounded by punctuation characters or space. Sometime this regex works fine, but in this case it also includes quote and dot int the match. What's wrong with it? Maybe there is a better idea?
You can use
\bidentifi.*?\b
Which means:
'foo "bar identifier"'.match(/\bidentifi.*?\b/g); // ["identifier"]
'foo identififfiieer. bar'.match(/\bidentifi.*?\b/g); // ["identififfiieer"]
You can use \\w*identifi\\w*
\\w
stands for "word character". It always matches the ASCII characters[A-Za-z0-9_]
. Notice the inclusion of the underscore and digits.
Here is a demo, showing the regex and its matches.
As a side note, your original regex actually works fine if you use the capturing group:
var body = 'If it bothers you, call it a "const identifier" instead.\nIt doesn\'t matter whether you call max a const variable or a const identififfiieer. What matters...';
var reg = /[\ ,!@#$%^&*()\.\"]*(identifi.*?)[\ ,!@#$%^&*()\d\.\"]/g;
var match;
while (match = reg.exec(body)) {
console.log('>' + match[1] + '<');
}
This outputs:
>identifier<
>identififfiieer<
Here 'sa demo for this code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.