2017-08-21 22 views
-1

我有一个JavaScript字符串的正则表达式:用于去除特定字符只有在有两边空格字符

var myString= "word = another : more new: one = two"; 

我想弄清楚,会产生这样的正则表达式:

var myString= "word another more new: one two"; 

所以当一个空格后跟一个=符号然后跟着另一个空格的模式会导致=符号被删除。

对于:字符也是如此。

如果=字符或:字符被删除,那很好,或者如果这些字符被替换为空格字符也很好。

总结要替换多个出现的=或a:当且仅当他们围绕着一个空格字符 。

无论哪个正则表达式更容易编写。

+3

'yourstring.replace(/ [=:] /克,'“)' –

回答

0

//save the appropriate RegEx in the variable re 
 
//It looks for a space followed by either a colon or equals sign 
 
// followed by another space 
 
    let re = /(\s(=|:)\s)/g; 
 

 
//load test string into variable string 
 
    let string = "word = another : more new: one = two"; 
 
//parse the string and replace any matches with a space 
 
    let parsed_string = string.replace(re, " "); 
 

 
//show result in the DOM 
 
    document.body.textContent = string + " => " + parsed_string;

+0

注意,使用一个字符类'[=:]'是内比交替_much_更有效捕获组'(= |:)' - 并将整个事件包含在另一个捕获组中/(...)/ g'只是增加了你不需要的开销,因为你没有对捕获进行任何操作。 .'s'是_any_空格,不仅仅是空格,但是这种改变可能更加合意。 –

1

不使用JavaScript ...但你的想法:

echo "word = another : more new: one = two" | sed 's/ [:=]//g' 

返回所需的字符串:

word another more new: one two 

说明:表达/ [:=] /找到所有“空格,然后以冒号还是equals标志后跟空格“并替换为”空格“。

相关问题