RegEx for exact word search starting with Umlaut [duplicate] - javascript
I am building search and I am going to use javascript autocomplete with it. I am from Finland (finnish language) so I have to deal with some special characters like ä, ö and å
When user types text in to the search input field I try to match the text to data.
Here is simple example that is not working correctly if user types for example "ää". Same thing with "äl"
var title = "this is simple string with finnish word tämä on ääkköstesti älkää ihmetelkö";
// Does not work
var searchterm = "äl";
// does not work
//var searchterm = "ää";
// Works
//var searchterm = "wi";
if ( new RegExp("\\b"+searchterm, "gi").test(title) ) {
$("#result").html("Match: ("+searchterm+"): "+title);
} else {
$("#result").html("nothing found with term: "+searchterm);
}
http://jsfiddle.net/7TsxB/
So how can I get those ä,ö and å characters to work with javascript regex?
I think I should use unicode codes but how should I do that? Codes for those characters are:
[\u00C4,\u00E4,\u00C5,\u00E5,\u00D6,\u00F6]
=> äÄåÅöÖ
There appears to be a problem with Regex and the word boundary \b matching the beginning of a string with a starting character out of the normal 256 byte range.
Instead of using \b, try using (?:^|\\s)
var title = "this is simple string with finnish word tämä on ääkköstesti älkää ihmetelkö";
// Does not work
var searchterm = "äl";
// does not work
//var searchterm = "ää";
// Works
//var searchterm = "wi";
if ( new RegExp("(?:^|\\s)"+searchterm, "gi").test(title) ) {
$("#result").html("Match: ("+searchterm+"): "+title);
} else {
$("#result").html("nothing found with term: "+searchterm);
}
Breakdown:
(?: parenthesis () form a capture group in Regex. Parenthesis started with a question mark and colon ?: form a non-capturing group. They just group the terms together
^ the caret symbol matches the beginning of a string
| the bar is the "or" operator.
\s matches whitespace (appears as \\s in the string because we have to escape the backslash)
) closes the group
So instead of using \b, which matches word boundaries and doesn't work for unicode characters, we use a non-capturing group which matches the beginning of a string OR whitespace.
The \b character class in JavaScript RegEx is really only useful with simple ASCII encoding. \b is a shortcut code for the boundary between \w and \W sets or \w and the beginning or end of the string. These character sets only take into account ASCII "word" characters, where \w is equal to [a-zA-Z0-9_] and \W is the negation of that class.
This makes the RegEx character classes largely useless for dealing with any real language.
\s should work for what you want to do, provided that search terms are only delimited by whitespace.
this question is old, but I think I found a better solution for boundary in regular expressions with unicode letters.
Using XRegExp library you can implement a valid \b boundary expanding this
XRegExp('(?=^|$|[^\\p{L}])')
the result is a 4000+ char long, but it seems to work quite performing.
Some explanation: (?= ) is a zero-length lookahead that looks for a begin or end boundary or a non-letter unicode character. The most important think is the lookahead, because the \b doesn't capture anything: it is simply true or false.
\b is a shortcut for the transition between a letter and a non-letter character, or vice-versa.
Updating and improving on max_masseti's answer:
With the introduction of the /u modifier for RegExs in ES2018, you can now use \p{L} to represent any unicode letter, and \P{L} (notice the uppercase P) to represent anything but.
EDIT: Previous version was incomplete.
As such:
const text = 'A Fé, o Império, e as terras viciosas';
text.split(/(?<=\p{L})(?=\P{L})|(?<=\P{L})(?=\p{L})/);
// ['A', ' Fé', ',', ' o', ' Império', ',', ' e', ' as', ' terras', ' viciosas']
We're using a lookbehind (?<=...) to find a letter and a lookahead (?=...) to find a non-letter, or vice versa.
I would recommend you to use XRegExp when you have to work with a specific set of characters from Unicode, the author of this library mapped all kind of regional sets of characters making the work with different languages easier.
Despite the fact the issue seems to be 8 years old, I run into a similar problem (I had to match Cyrillic letters) not so far ago. I spend a whole day on this and could not find any appropriate answer here on StackOverflow. So, to avoid others making lots of effort, I'd like to share my solution.
Yes, \b word boundary works only with Latin letters (Word boundary: \b):
Word boundary \b doesn’t work for non-Latin alphabets
The word boundary test \b checks that there should be \w on the one side from the position and "not \w" – on the other side.
But \w means a Latin letter a-z (or a digit or an underscore), so the test doesn’t work for other characters, e.g. Cyrillic letters or hieroglyphs.
Yes, JavaScript RegExp implementation hardly supports UTF-8 encoding.
So, I tried implementing own word boundary feature with the support of non-Latin characters. To make word boundary work just with Cyrillic characters I created such regular expression:
new RegExp(`(?<![\u0400-\u04ff])${cyrillicSearchValue}(?![\u0400-\u04ff])`,'gi')
Where \u0400-\u04ff is a range of Cyrillic characters provided in the table of codes. It is not an ideal solution, however, it works properly in most cases.
To make it work in your case, you just have to pick up an appropriate range of codes from the list of Unicode characters.
To try out my example run the code snippet below.
function getMatchExpression(cyrillicSearchValue) {
return new RegExp(
`(?<![\u0400-\u04ff])${cyrillicSearchValue}(?![\u0400-\u04ff])`,
'gi',
);
}
const sentence = 'Будь-який текст кирилицею, де необхідно знайти слово з контексту';
console.log(sentence.match(getMatchExpression('текст')));
// expected output: ["текст"]
console.log(sentence.match(getMatchExpression('но')));
// expected output: null
I noticed something really weird with \b when using Unicode:
/\bo/.test("pop"); // false (obviously)
/\bä/.test("päp"); // true (what..?)
/\Bo/.test("pop"); // true
/\Bä/.test("päp"); // false (what..?)
It appears that meaning of \b and \B are reversed, but only when used with non-ASCII Unicode? There might be something deeper going on here, but I'm not sure what it is.
In any case, it seems that the word boundary is the issue, not the Unicode characters themselves. Perhaps you should just replace \b with (^|[\s\\/-_&]), as that seems to work correctly. (Make your list of symbols more comprehensive than mine, though.)
My idea is to search with codes representing the Finnish letters
new RegExp("\\b"+asciiOnly(searchterm), "gi").test(asciiOnly(title))
My original idea was to use plain encodeURI but the % sign seemed to interfere with the regexp.
http://jsfiddle.net/7TsxB/5/
I wrote a crude function using encodeURI to encode every character with code over 128 but removing its % and adding 'QQ' in the beginning. It is not the best marker but I couldn't get non alphanumeric to work.
What you are looking for is the Unicode word boundaries standard:
http://unicode.org/reports/tr29/tr29-9.html#Word_Boundaries
There is a JavaScript implementation here (unciodejs.wordbreak.js)
https://github.com/wikimedia/unicodejs
I had a similar problem, where I was trying to replace all of a particular unicode word with a different unicode word, and I cannot use lookbehind because it's not supported in the JS engine this code will be used in. I ultimately resolved it like this:
const needle = "КАРТОПЛЯ";
const replace = "БАРАБОЛЯ";
const regex = new RegExp(
String.raw`(^|[^\n\p{L}])`
+ needle
+ String.raw`(?=$|\P{L})`,
"gimu",
);
const result = (
'КАРТОПЛЯ сдффКАРТОПЛЯдадф КАРТОПЛЯ КАРТОПЛЯ КАРТОПЛЯ??? !!!КАРТОПЛЯ ;!;!КАРТОПЛЯ/#?#?'
+ '\n\nКАРТОПЛЯ КАРТОПЛЯ - - -КАРТОПЛЯ--'
)
.replace(regex, function (match, ...args) {
return args[0] + replace;
});
console.log(result)
output:
БАРАБОЛЯ сдффКАРТОПЛЯдадф БАРАБОЛЯ БАРАБОЛЯ БАРАБОЛЯ??? !!!БАРАБОЛЯ ;!;!БАРАБОЛЯ/#?#?
БАРАБОЛЯ БАРАБОЛЯ - - -БАРАБОЛЯ--
Breaking it apart
The first regex: (^|[^\n\p{L}])
^| = Start of the line or
[^\n\p{L}] = Any character which is not a letter or a newline
The second regex: (?=$|\P{L})
?= = Lookahead
$| = End of the line or
\P{L} = Any character which is not a letter
The first regex captures the group and is then used via args[0] to put it back into the string during replacement, thereby avoiding a lookbehind. The second regex utilized lookahead.
Note that the second one MUST be a lookahead because if we capture it then overlapping regex matches will not trigger (e.g. КАРТОПЛЯ КАРТОПЛЯ КАРТОПЛЯ would only match on the 1st and 3rd ones).
Trying to find text "myTest":
/(?<![\p{L}\p{N}_])myTest(?![\p{L}\p{N}_])/gu
Similar to NetBeans or Notepad++ form. Trying to find the expression without any letter or number or underscore (like \w characters of word boundary \b) in any unicode characters of letter and number before or after the expression.
I have had a similar problem, but I had to replace an array of terms. All solutions, which I have found did not worked, if two terms were in the text next to each other (because their boundaries overlaped). So I had to use a little modified approach:
var text = "Ještě. že; \"už\" à. Fürs, 'anlässlich' že že že.";
var terms = ["à","anlässlich","Fürs","už","Ještě", "že"];
var replaced = [];
var order = 0;
for (i = 0; i < terms.length; i++) {
terms[i] = "(^\|[ \n\r\t.,;'\"\+!?-])(" + terms[i] + ")([ \n\r\t.,;'\"\+!?-]+\|$)";
}
var re = new RegExp(terms.join("|"), "");
while (true) {
var replacedString = "";
text = text.replace(re, function replacer(match){
var beginning = match.match("^[ \n\r\t.,;'\"\+!?-]+");
if (beginning == null) beginning = "";
var ending = match.match("[ \n\r\t.,;'\"\+!?-]+$");
if (ending == null) ending = "";
replacedString = match.replace(beginning,"");
replacedString = replacedString.replace(ending,"");
replaced.push(replacedString);
return beginning+"{{"+order+"}}"+ending;
});
if (replacedString == "") break;
order += 1;
}
See the code in a fiddle: http://jsfiddle.net/antoninslejska/bvbLpdos/1/
The regular expression is inspired by: http://breakthebit.org/post/3446894238/word-boundaries-in-javascripts-regular
I can't say, that I find the solution elegant...
The correct answer to the question is given by andrefs.
I will only rewrite it more clearly, after putting all required things together.
For ASCII text, you can use \b for matching a word boundary both at the start and the end of a pattern. When using Unicode text, you need to use 2 different patterns for doing the same:
Use (?<=^|\P{L}) for matching the start or a word boundary before the main pattern.
Use (?=\P{L}|$) for matching the end or a word boundary after the main pattern.
Additionally, use (?i) in the beginning of everything, to make all those matchings case-insensitive.
So the resulting answer is: (?i)(?<=^|\P{L})xxx(?=\P{L}|$), where xxx is your main pattern. This would be the equivalent of (?i)\bxxx\b for ASCII text.
For your code to work, you now need to do the following:
Assign to your variable "searchterm", the pattern or words you want to find.
Escape the variable's contents. For example, replace '\' with '\\' and also do the same for any reserved special character of regex, like '\^', '\$', '\/', etc. Check here for a question on how to do this.
Insert the variable's contents to the pattern above, in the place of "xxx", by simply using the string.replace() method.
bad but working:
var text = " аб аб АБ абвг ";
var ttt = "(аб)"
var p = "(^|$|[^A-Za-zА-Я-а-я0-9()])"; // add other word boundary symbols here
var exp = new RegExp(p+ttt+p,"gi");
text = text.replace(exp, "$1($2)$3").replace(exp, "$1($2)$3");
const t1 = performance.now();
console.log(text);
result (without qutes):
" (аб) (аб) (АБ) абвг "
I struggled hard on this. Working with French accented characters, and I managed to find this solution :
const myString = "MyString";
const regex = new RegExp(
"(?:[^À-ú]|^)\\b(" + myString + ")\\b(?:[^À-ú]|$)",
"ig"
);
What id does :
It keeps checking word-boundaries with \b before and after "MyString".
In addition to that, (?:[^À-ú]|^) and (?:[^À-ú]|$) will check if MyString is not surrounded by any accented characters
It will not work with cyrillic but it may be possible to find the range of cirillic charactes and edit [^À-ú] in consequence.
Warning, it captures only the group (MyString) but the total match contains previous and next characters
See example : https://regex101.com/r/5P0ZIe/1
Match examples :
MyString
match : "MyString"
group 1 : "MyString"
Lorem ipsum. MyString dolor sit amet
match : " MyString "
group 1 : "MyString"
(MyString)
match : "(MyString)"
group 1 : "MyString"
BetweenCharactersMyStringIsNotFound
match : Nothing
group 1 : Nothing
éMyStringé
match : Nothing
group 1 : Nothing
ùMyString
match : Nothing
group 1 : Nothing
MyStringÖ
match : Nothing
group 1 : Nothing
Related
Multiword RegEx containing '/' is not correctly finding the term
Hey there I'm trying to write a multi-word RegEx that uses word boundaries. The string I'm searching is as follows (this is only a test string): const regString = "/gamma/ truck?timer!doctor\\face" Here is my regular expression: const testReg2 = new RegExp("\\b\/gamma/|truck|\\?|face\\b", "gi"); For whatever reason the console posts ['truck', '?', 'face'] but it refuses to find '/gamma/' which is puzzling because const testReg = new RegExp("/gamma/"); does find '/gamma/'. const regString = "/gamma/ truck?timer!doctor\\face" const testReg2 = new RegExp("\\b\/gamma/|truck|\\?|face\\b", "gi"); console.log(regString.match(testReg2))
The issue is in using \b\/gamma and expecting it to match "/gamma" (same for the closing \b). The Word Boundary \b in order to work it should be followed (or preceded, depending on where it's used) by at least one (or more) Word characters. Which is not — due to the non-word / character. To visualize, let's spread those characters: # Regex: \bxyz / g a m m a ^--------- \b points here. Match: `gamma` # Regex: \b\/xyz / g a m m a \b points nowhere. Match: none since `/` is a non-word char Either: remove the \/ since that's already a specific character prefix / suffix, or... If you really need to make sure the exact existance and sequence of those characters /gamma/, than don't use \b for the /gamma/ case. \/gamma\/|\b(truck|\?|face)\b Example on Regex101.com const regString = "/gamma/ truck?timer!doctor\\face" console.log(regString.match(/\/gamma\/|\b(truck|\?|face)\b/gi))
There are two ways to make this work, a) using word boundaries with words that start/end with word chars only (when the words are know beforehand, it is the easiest way), or b) using adaptive dynamic word boundaries (this is good if your "word" list is dynamic, or user-defined). Here is Option 1: const regString = "/gamma/ truck?timer!doctor\\face" const testReg2 = /\/gamma\/|\?|\b(?:truck|face)\b/gi; console.log(regString.match(testReg2)) So, here, ? and /gamma/ are NOT checked if they are whole words or not, since they start/end with non-word chars. Now, Option 2: const regString = "/gamma/ truck?timer!doctor\\face"; const words = ["/gamma/", "?", "truck", "face"]; const testReg2 = new RegExp("(?!\\B\\w)(?:" + words.map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join("|") + ")(?<!\\w\\B)", "gi"); console.log(regString.match(testReg2)); This solution requires the lookbehind support, but it makes sure the whole word check is applied only in case there are word chars at the start/end of the word (also, all special chars are escaped appropriately).
According to this answer [...] at the beginning or end of a string if it begins or ends (respectively) with a word character ([0-9A-Za-z_]) Your string doesn't start with [0-9A-Za-z_] hence not match
Regex treating accentuated letters as word boundary [duplicate]
I am building search and I am going to use javascript autocomplete with it. I am from Finland (finnish language) so I have to deal with some special characters like ä, ö and å When user types text in to the search input field I try to match the text to data. Here is simple example that is not working correctly if user types for example "ää". Same thing with "äl" var title = "this is simple string with finnish word tämä on ääkköstesti älkää ihmetelkö"; // Does not work var searchterm = "äl"; // does not work //var searchterm = "ää"; // Works //var searchterm = "wi"; if ( new RegExp("\\b"+searchterm, "gi").test(title) ) { $("#result").html("Match: ("+searchterm+"): "+title); } else { $("#result").html("nothing found with term: "+searchterm); } http://jsfiddle.net/7TsxB/ So how can I get those ä,ö and å characters to work with javascript regex? I think I should use unicode codes but how should I do that? Codes for those characters are: [\u00C4,\u00E4,\u00C5,\u00E5,\u00D6,\u00F6] => äÄåÅöÖ
There appears to be a problem with Regex and the word boundary \b matching the beginning of a string with a starting character out of the normal 256 byte range. Instead of using \b, try using (?:^|\\s) var title = "this is simple string with finnish word tämä on ääkköstesti älkää ihmetelkö"; // Does not work var searchterm = "äl"; // does not work //var searchterm = "ää"; // Works //var searchterm = "wi"; if ( new RegExp("(?:^|\\s)"+searchterm, "gi").test(title) ) { $("#result").html("Match: ("+searchterm+"): "+title); } else { $("#result").html("nothing found with term: "+searchterm); } Breakdown: (?: parenthesis () form a capture group in Regex. Parenthesis started with a question mark and colon ?: form a non-capturing group. They just group the terms together ^ the caret symbol matches the beginning of a string | the bar is the "or" operator. \s matches whitespace (appears as \\s in the string because we have to escape the backslash) ) closes the group So instead of using \b, which matches word boundaries and doesn't work for unicode characters, we use a non-capturing group which matches the beginning of a string OR whitespace.
The \b character class in JavaScript RegEx is really only useful with simple ASCII encoding. \b is a shortcut code for the boundary between \w and \W sets or \w and the beginning or end of the string. These character sets only take into account ASCII "word" characters, where \w is equal to [a-zA-Z0-9_] and \W is the negation of that class. This makes the RegEx character classes largely useless for dealing with any real language. \s should work for what you want to do, provided that search terms are only delimited by whitespace.
this question is old, but I think I found a better solution for boundary in regular expressions with unicode letters. Using XRegExp library you can implement a valid \b boundary expanding this XRegExp('(?=^|$|[^\\p{L}])') the result is a 4000+ char long, but it seems to work quite performing. Some explanation: (?= ) is a zero-length lookahead that looks for a begin or end boundary or a non-letter unicode character. The most important think is the lookahead, because the \b doesn't capture anything: it is simply true or false.
\b is a shortcut for the transition between a letter and a non-letter character, or vice-versa. Updating and improving on max_masseti's answer: With the introduction of the /u modifier for RegExs in ES2018, you can now use \p{L} to represent any unicode letter, and \P{L} (notice the uppercase P) to represent anything but. EDIT: Previous version was incomplete. As such: const text = 'A Fé, o Império, e as terras viciosas'; text.split(/(?<=\p{L})(?=\P{L})|(?<=\P{L})(?=\p{L})/); // ['A', ' Fé', ',', ' o', ' Império', ',', ' e', ' as', ' terras', ' viciosas'] We're using a lookbehind (?<=...) to find a letter and a lookahead (?=...) to find a non-letter, or vice versa.
I would recommend you to use XRegExp when you have to work with a specific set of characters from Unicode, the author of this library mapped all kind of regional sets of characters making the work with different languages easier.
Despite the fact the issue seems to be 8 years old, I run into a similar problem (I had to match Cyrillic letters) not so far ago. I spend a whole day on this and could not find any appropriate answer here on StackOverflow. So, to avoid others making lots of effort, I'd like to share my solution. Yes, \b word boundary works only with Latin letters (Word boundary: \b): Word boundary \b doesn’t work for non-Latin alphabets The word boundary test \b checks that there should be \w on the one side from the position and "not \w" – on the other side. But \w means a Latin letter a-z (or a digit or an underscore), so the test doesn’t work for other characters, e.g. Cyrillic letters or hieroglyphs. Yes, JavaScript RegExp implementation hardly supports UTF-8 encoding. So, I tried implementing own word boundary feature with the support of non-Latin characters. To make word boundary work just with Cyrillic characters I created such regular expression: new RegExp(`(?<![\u0400-\u04ff])${cyrillicSearchValue}(?![\u0400-\u04ff])`,'gi') Where \u0400-\u04ff is a range of Cyrillic characters provided in the table of codes. It is not an ideal solution, however, it works properly in most cases. To make it work in your case, you just have to pick up an appropriate range of codes from the list of Unicode characters. To try out my example run the code snippet below. function getMatchExpression(cyrillicSearchValue) { return new RegExp( `(?<![\u0400-\u04ff])${cyrillicSearchValue}(?![\u0400-\u04ff])`, 'gi', ); } const sentence = 'Будь-який текст кирилицею, де необхідно знайти слово з контексту'; console.log(sentence.match(getMatchExpression('текст'))); // expected output: ["текст"] console.log(sentence.match(getMatchExpression('но'))); // expected output: null
I noticed something really weird with \b when using Unicode: /\bo/.test("pop"); // false (obviously) /\bä/.test("päp"); // true (what..?) /\Bo/.test("pop"); // true /\Bä/.test("päp"); // false (what..?) It appears that meaning of \b and \B are reversed, but only when used with non-ASCII Unicode? There might be something deeper going on here, but I'm not sure what it is. In any case, it seems that the word boundary is the issue, not the Unicode characters themselves. Perhaps you should just replace \b with (^|[\s\\/-_&]), as that seems to work correctly. (Make your list of symbols more comprehensive than mine, though.)
My idea is to search with codes representing the Finnish letters new RegExp("\\b"+asciiOnly(searchterm), "gi").test(asciiOnly(title)) My original idea was to use plain encodeURI but the % sign seemed to interfere with the regexp. http://jsfiddle.net/7TsxB/5/ I wrote a crude function using encodeURI to encode every character with code over 128 but removing its % and adding 'QQ' in the beginning. It is not the best marker but I couldn't get non alphanumeric to work.
What you are looking for is the Unicode word boundaries standard: http://unicode.org/reports/tr29/tr29-9.html#Word_Boundaries There is a JavaScript implementation here (unciodejs.wordbreak.js) https://github.com/wikimedia/unicodejs
I had a similar problem, where I was trying to replace all of a particular unicode word with a different unicode word, and I cannot use lookbehind because it's not supported in the JS engine this code will be used in. I ultimately resolved it like this: const needle = "КАРТОПЛЯ"; const replace = "БАРАБОЛЯ"; const regex = new RegExp( String.raw`(^|[^\n\p{L}])` + needle + String.raw`(?=$|\P{L})`, "gimu", ); const result = ( 'КАРТОПЛЯ сдффКАРТОПЛЯдадф КАРТОПЛЯ КАРТОПЛЯ КАРТОПЛЯ??? !!!КАРТОПЛЯ ;!;!КАРТОПЛЯ/#?#?' + '\n\nКАРТОПЛЯ КАРТОПЛЯ - - -КАРТОПЛЯ--' ) .replace(regex, function (match, ...args) { return args[0] + replace; }); console.log(result) output: БАРАБОЛЯ сдффКАРТОПЛЯдадф БАРАБОЛЯ БАРАБОЛЯ БАРАБОЛЯ??? !!!БАРАБОЛЯ ;!;!БАРАБОЛЯ/#?#? БАРАБОЛЯ БАРАБОЛЯ - - -БАРАБОЛЯ-- Breaking it apart The first regex: (^|[^\n\p{L}]) ^| = Start of the line or [^\n\p{L}] = Any character which is not a letter or a newline The second regex: (?=$|\P{L}) ?= = Lookahead $| = End of the line or \P{L} = Any character which is not a letter The first regex captures the group and is then used via args[0] to put it back into the string during replacement, thereby avoiding a lookbehind. The second regex utilized lookahead. Note that the second one MUST be a lookahead because if we capture it then overlapping regex matches will not trigger (e.g. КАРТОПЛЯ КАРТОПЛЯ КАРТОПЛЯ would only match on the 1st and 3rd ones).
Trying to find text "myTest": /(?<![\p{L}\p{N}_])myTest(?![\p{L}\p{N}_])/gu Similar to NetBeans or Notepad++ form. Trying to find the expression without any letter or number or underscore (like \w characters of word boundary \b) in any unicode characters of letter and number before or after the expression.
I have had a similar problem, but I had to replace an array of terms. All solutions, which I have found did not worked, if two terms were in the text next to each other (because their boundaries overlaped). So I had to use a little modified approach: var text = "Ještě. že; \"už\" à. Fürs, 'anlässlich' že že že."; var terms = ["à","anlässlich","Fürs","už","Ještě", "že"]; var replaced = []; var order = 0; for (i = 0; i < terms.length; i++) { terms[i] = "(^\|[ \n\r\t.,;'\"\+!?-])(" + terms[i] + ")([ \n\r\t.,;'\"\+!?-]+\|$)"; } var re = new RegExp(terms.join("|"), ""); while (true) { var replacedString = ""; text = text.replace(re, function replacer(match){ var beginning = match.match("^[ \n\r\t.,;'\"\+!?-]+"); if (beginning == null) beginning = ""; var ending = match.match("[ \n\r\t.,;'\"\+!?-]+$"); if (ending == null) ending = ""; replacedString = match.replace(beginning,""); replacedString = replacedString.replace(ending,""); replaced.push(replacedString); return beginning+"{{"+order+"}}"+ending; }); if (replacedString == "") break; order += 1; } See the code in a fiddle: http://jsfiddle.net/antoninslejska/bvbLpdos/1/ The regular expression is inspired by: http://breakthebit.org/post/3446894238/word-boundaries-in-javascripts-regular I can't say, that I find the solution elegant...
The correct answer to the question is given by andrefs. I will only rewrite it more clearly, after putting all required things together. For ASCII text, you can use \b for matching a word boundary both at the start and the end of a pattern. When using Unicode text, you need to use 2 different patterns for doing the same: Use (?<=^|\P{L}) for matching the start or a word boundary before the main pattern. Use (?=\P{L}|$) for matching the end or a word boundary after the main pattern. Additionally, use (?i) in the beginning of everything, to make all those matchings case-insensitive. So the resulting answer is: (?i)(?<=^|\P{L})xxx(?=\P{L}|$), where xxx is your main pattern. This would be the equivalent of (?i)\bxxx\b for ASCII text. For your code to work, you now need to do the following: Assign to your variable "searchterm", the pattern or words you want to find. Escape the variable's contents. For example, replace '\' with '\\' and also do the same for any reserved special character of regex, like '\^', '\$', '\/', etc. Check here for a question on how to do this. Insert the variable's contents to the pattern above, in the place of "xxx", by simply using the string.replace() method.
bad but working: var text = " аб аб АБ абвг "; var ttt = "(аб)" var p = "(^|$|[^A-Za-zА-Я-а-я0-9()])"; // add other word boundary symbols here var exp = new RegExp(p+ttt+p,"gi"); text = text.replace(exp, "$1($2)$3").replace(exp, "$1($2)$3"); const t1 = performance.now(); console.log(text); result (without qutes): " (аб) (аб) (АБ) абвг "
I struggled hard on this. Working with French accented characters, and I managed to find this solution : const myString = "MyString"; const regex = new RegExp( "(?:[^À-ú]|^)\\b(" + myString + ")\\b(?:[^À-ú]|$)", "ig" ); What id does : It keeps checking word-boundaries with \b before and after "MyString". In addition to that, (?:[^À-ú]|^) and (?:[^À-ú]|$) will check if MyString is not surrounded by any accented characters It will not work with cyrillic but it may be possible to find the range of cirillic charactes and edit [^À-ú] in consequence. Warning, it captures only the group (MyString) but the total match contains previous and next characters See example : https://regex101.com/r/5P0ZIe/1 Match examples : MyString match : "MyString" group 1 : "MyString" Lorem ipsum. MyString dolor sit amet match : " MyString " group 1 : "MyString" (MyString) match : "(MyString)" group 1 : "MyString" BetweenCharactersMyStringIsNotFound match : Nothing group 1 : Nothing éMyStringé match : Nothing group 1 : Nothing ùMyString match : Nothing group 1 : Nothing MyStringÖ match : Nothing group 1 : Nothing
regular expression to match special characters between delimiters
i have a basic string and would like to get only specific charaters between the brackets Base string: This is a test string [more or less] regex: to capture all r's and e's works just fine. (r|e) => This is a test string [more or less] Now i want to use the following regex and group it with my regex to give only r's and e's between the brackets, but unfortunately this doesn't work: \[(r|e)\] Expected result should be : more or less can someone explain? edit: the problem is very similar to this one: Regular Expression to find a string included between two characters while EXCLUDING the delimiters but with the difference, that i don't want to get the whole string between the brackets. Follow up problem base string = 'this is a link:/en/test/äpfel/öhr[MyLink_with_äöü] BREAK äöü is now allowed' I need a regex for finding the non-ascii characters äöü in order to replace them but only in the link:...] substring which starts with the word link: and ends with a ] char. The result string will look like this: result string = 'this is a link:/en/test/apfel/ohr[MyLink_with_aou] BREAK äöü is now allowed again' The regex /[äöü]+(?=[^\]\[]*])/g from the solution in the comments only delivers the äöü chars between the two brackets. I know that there is a forward lookahead with a char list in the regex, but i wonder why this one does not work: /link:([äöü]+(?=[^\]\[]*])/ thanks
You can use the following solution: match all between link: and ], and replace your characters only inside the matched substrings inside a replace callback method: var hashmap = {"ä":"a", "ö":"o", "ü":"u"}; var s = 'this is a link:/en/test/äpfel/öhr[MyLink_with_äöü] BREAK äöü is now allowed'; var res = s.replace(/\blink:[^\]]*/g, function(m) { // m = link:/en/test/äpfel/öhr[MyLink_with_äöü] return m.replace(/[äöü]/g, function(n) { // n = ä, then ö, then ü, return hashmap[n]; // each time replaced with the hashmap value }); }); console.log(res); Pattern details: \b - a leading word boundary link: - whole word link with a : after it [^\]]* - zero or more chars other than ] (a [^...] is a negated character class that matches any char/char range(s) but the ones defined inside it). Also, see Efficiently replace all accented characters in a string?
Do word boundaries work on symbol characters?
I'm trying to implement word boundaries in my emoticons feature for a chat. But for some reason I can't seem to get the word boundaries to work. I am new to regex. So when I do: var reg = /\b\Hi\b/gi; var str = 'HiHiHi Hi HiHiHi Hi'; alert(str.replace(reg, '')); This happens: Jsfiddle It actually works fine, and does remove those 2 Hi's that are standing alone. But when I change the reg to an escaped smiley and then change the string: var reg = /\b\:\)\b/gi; var str = 'HiHi:) :) HiHiHi :)'; alert(str.replace(reg, '')); This happens: Jsfiddle It just doesn't work. The string stays the same. Is it that word boundaries can't be used on symbols? If so, how does Facebook do it on their chats?
Word boundaries \b represent a zero-width boundary between word characters \w (in javascript, [A-Za-z_]) and non-word characters \W (everything else). Because of this, there will not be a boundary between two emoticons or when the emoticon is surrounded by spaces, punctuation, etc. The simplest regex would be /[:;]-?[()]/gi, which supports smileys ) and frownies ( with optional dashes and eyes : or winks ;. Edit: This will require either a space or the beginning of the string (as a capturing group since Javascript doesn't support look-behinds), then it uses the above regex, then it must be followed by the end of string or whitespace. var reg = /(\s|^)[:;]-?[()](?:\s|$)/gi; var str = 'HiHi:) :) HiHiHi :)'; alert(str.replace(reg, '$1')); Should replace in these situations: :-), cool :( not! Should not replace in these situations: Digits:(0,1,2,3), hi :(.
As \b will not work in this case, you could use: var re = /(\s|^):\)(?!\S)/g; var str = 'HiHi:) :) HiHiHi :)'; alert(str.replace(re, '$1')); Which works like a space boundary. You can add several smileys to it like so: /(\s|^)(?::\)|:\(|:\||:\]|:\[)(?!\S)/g;
Regex to remove non-letter characters but keep accented letters
I have strings in Spanish and other languages that may contain generic special characters like (),*, etc. That I need to remove. But the problem is that it also may contain special language characters like ñ, á, ó, í etc and they need to remain. So I am trying to do it with regexp the following way: var desired = stringToReplace.replace(/[^\w\s]/gi, ''); Unfortunately it is removing all special characters including the language related. Not sure how to avoid that. Maybe someone could suggest?
I would suggest using Steven Levithan's excellent XRegExp library and its Unicode plug-in. Here's an example that strips non-Latin word characters from a string: http://jsfiddle.net/b3awZ/1/ var regex = XRegExp("[^\\s\\p{Latin}]+", "g"); var str = "¿Me puedes decir la contraseña de la Wi-Fi?" var replaced = XRegExp.replace(str, regex, ""); See also this answer by Steven Levithan himself: Regular expression Spanish and Arabic words
Instead of whitelisting characters you accept, you could try blacklisting illegal characters: var desired = stringToReplace.replace(/[-'`~!##$%^&*()_|+=?;:'",.<>\{\}\[\]\\\/]/gi, '')
Note! Works only for 16bit code points. This answer is incomplete. Short answer The character class for all arabic digits and latin letters is: [0-9A-Za-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02af\u1d00-\u1d25\u1d62-\u1d65\u1d6b-\u1d77\u1d79-\u1d9a\u1e00-\u1eff\u2090-\u2094\u2184-\u2184\u2488-\u2490\u271d-\u271d\u2c60-\u2c7c\u2c7e-\u2c7f\ua722-\ua76f\ua771-\ua787\ua78b-\ua78c\ua7fb-\ua7ff\ufb00-\ufb06]. To get a regex you can use, prepend /^ and append +$/. This will match strings consisting of only latin letters and digits like "mérito" or "Schönheit". To match non-digits or non-letter characters to remove them, write a ^ as first character after the opening bracket [ and prepend / and append +/. How did I find that out? Continue reading. Long answer: use metaprogramming! Because Javascript does not have Unicode regexes, I wrote a Python program to iterate over the whole of Unicode and filter by Unicode name. It is difficult to get this right manually. Why not let the computer do the dirty and menial work? import unicodedata import re import sys def unicodeNameMatch(pattern, codepoint): try: return re.match(pattern, unicodedata.name(unichr(codepoint)), re.I) except ValueError: return None def regexChr(codepoint): return chr(codepoint) if 32 <= codepoint < 127 else "\\u%04x" % codepoint names = sys.argv prev = None js_regex = "" for codepoint in range(pow(2, 16)): if any([unicodeNameMatch(name, codepoint) for name in names]): if prev is None: js_regex += regexChr(codepoint) prev = codepoint else: if not prev is None: js_regex += "-" + regexChr(prev) prev = None print "[" + js_regex + "]" Invoke it like this: python char_class.py latin digit and you get the character class mentioned above. It's an ugly char class but you know for sure that you catched all characters whose names contain latin or digit. Browse the Unicode Character Database to view the names of all unicode characters. The name is in uppercase after the first semicolon, for example for A its the line 0041;LATIN CAPITAL LETTER A;Lu;0;L;;;;;N;;;;0061; Try python char_class.py "latin small" and you get a character class for all latin small letters. Edit: There is a small misfeature (aka bug) in that \u271d-\u271d occurs in the regex. Perhaps this fix helps: Replace if not prev is None: js_regex += "-" + regexChr(prev) by if not prev is None and prev != codepoint: js_regex += "-" + regexChr(prev)
var desired = stringToReplace.replace(/[\u0000-\u007F][\W]/gi, ''); might do the trick. See also this Javascript + Unicode regexes question.
If you must insist on whitelisting here is the rawest way of doing it: Test if string contains only letters (a-z + é ü ö ê å ø etc..) It works by keeping track of 'all' unicode letter chars.
Unfortunately, Javascript does not support Unicode character properties (which would be just the right regex feature for you). If changing the language is an option for you, PHP (for example) can do this: preg_replace("/[^\pL0-9_\s]/", "", $str); Where \pL matches any Unicode character that represents a letter (lower case, upper case, modified or unmodified). If you have to stick with JavaScript and cannot use the library suggested by Tim Down, the only options are probably either blacklisting or whitelisting. But your bounty mentions that blacklisting is not actually an option in your case. So you will probably simply have to include the special characters from your relevant language manually. So you could simply do this: var desired = stringToReplace.replace(/[^\w\sñáóí]/gi, ''); Or use their corresponding Unicode sequences: var desired = stringToReplace.replace(/[^\w\s\u00F1\u00C1\u00F3\u00ED]/gi, ''); Then simply add all the ones you want to take care of. Note that the case-insensitive modifier also works with Unicode sequences.