javascript 如何在Javascript中的正则表达式中添加空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24380261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:40:48  来源:igfitidea点击:

How to add white space in regular expression in Javascript

javascriptregex

提问by Nitish Kumar

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.

对此的任何解决方案。

回答by Avinash Raj

Give the word character\wand the space character\sinside 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. It matches one or more word or space character.

  • \}- Matches a literal }symbol.

  • \}- Matches a literal }symbol.

  • \{- 匹配文字{符号。

  • \{- 匹配文字{符号。

  • [\w\s]+- 在 Character 类中给出了单词字符和空格字符。它匹配一个或多个单词或空格字符。

  • \}- 匹配文字}符号。

  • \}- 匹配文字}符号。

回答by Naresh Ravlani

Try this on

试试这个

^\{\{[a-z]*\s[a-z]*\}\}$

Explanation:

解释:

  • \{ - Matches a literal { symbol.

  • \{ - Matches a literal { symbol.

  • [a-z]* - will match zero or more characters

  • \s - will match exact one space

  • \} - Matches a literal } symbol.

  • \} - Matches a literal } symbol.

  • \{ - 匹配文字 { 符号。

  • \{ - 匹配文字 { 符号。

  • [az]* - 将匹配零个或多个字符

  • \s - 将精确匹配一个空格

  • \} - 匹配文字 } 符号。

  • \} - 匹配文字 } 符号。

If you want compulsory character then use + instead of *.

如果您想要强制字符,请使用 + 而不是 *。

回答by zx81

To match this pattern, use this simple regex:

要匹配此模式,请使用以下简单的正则表达式:

{{[^}]+}}

The demoshows 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##代码##Something_else");

Explanation

解释

  • {{matches your two opening braces
  • [^}]+matches one or more chars that are not a closing brace
  • }}matches your two closing braces
  • {{匹配你的两个大括号
  • [^}]+匹配一个或多个不是右大括号的字符
  • }}匹配你的两个右大括号