[英]How to add white space in regular expression in Javascript
I have a string {{my name}}
and i want to add white space in regular expression 我有一个字符串{{my name}}
,我想在正则表达式中添加空格
var str = "{{my name}}";
var patt1 = /\{{\w{1,}\}}/gi;
var result = str.match(patt1);
console.log(result);
But result in not match. 但是结果不匹配。
Any solution for this. 任何解决方案。
Give the word character \\w
and the space character \\s
inside character class []
, 在字符类[]
给单词\\w
和空格\\s
,
> var patt1 = /\{\{[\w\s]+\}\}/gi;
undefined
> var result = str.match(patt1);
undefined
> console.log(result);
[ '{{my name}}' ]
The above regex is as same as /\\{\\{[\\w\\s]{1,}\\}\\}/gi
上面的正则表达式与/\\{\\{[\\w\\s]{1,}\\}\\}/gi
Explanation: 说明:
\\{
- Matches a literal {
symbol. \\{
-匹配文字{
符号。
\\{
- Matches a literal {
symbol. \\{
-匹配文字{
符号。
[\\w\\s]+
- word character and space character are given inside Character class. [\\w\\s]+
-字符类中提供了单词字符和空格字符。 It matches one or more word or space character. 它与一个或多个单词或空格字符匹配。
\\}
- Matches a literal }
symbol. \\}
-与文字}
符号匹配。
\\}
- Matches a literal }
symbol. \\}
-与文字}
符号匹配。
Try this on 试试这个
^\{\{[a-z]*\s[a-z]*\}\}$
Explanation: 说明:
\\{ - Matches a literal { symbol. \\ {-匹配文字{符号。
\\{ - Matches a literal { symbol. \\ {-匹配文字{符号。
[az]* - will match zero or more characters [az] *-将匹配零个或多个字符
\\s - will match exact one space \\ s-将精确匹配一个空格
\\} - Matches a literal } symbol. \\}-与文字}符号匹配。
\\} - Matches a literal } symbol. \\}-与文字}符号匹配。
If you want compulsory character then use + instead of *. 如果要使用强制字符,请使用+代替*。
To match this pattern, use this simple regex: 要匹配此模式,请使用以下简单的正则表达式:
{{[^}]+}}
The demo shows you what the pattern matches and doesn't match. 该演示向您展示了模式匹配和不匹配的内容。
In JS: 在JS中:
match = subject.match(/{{[^}]+}}/);
To do a replacement around the pattern, use this: 要围绕模式进行替换,请使用以下命令:
result = subject.replace(/{{[^}]+}}/g, "Something$0Something_else");
Explanation 说明
{{
matches your two opening braces {{
与您的两个大括号匹配 [^}]+
matches one or more chars that are not a closing brace [^}]+
匹配一个或多个不是大括号的字符 }}
matches your two closing braces }}
匹配您的两个右括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.