只有在任一侧有空格字符时才能删除某些字符的正则表达式

时间:2022-08-09 20:13:22

I have a Javascript string:

我有一个Javascript字符串:

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

I am trying to figure out a regex that would produce this:

我试图找出一个可以产生这个的正则表达式:

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

So when the pattern of a space followed by a = sign then followed by another space would result in the = sign being removed.

因此,当空格的模式后跟a =符号后跟另一个空格时,将导致删除=符号。

Likewise for the : character as well.

同样对于:角色也是如此。

If the = character or the : character are removed that is fine or if those characters are replaced by a space character that is fine as well.

如果删除了=字符或:字符,那么这些字符也可以用空格字符替换。

In summary to replace multiple occurrences of an = or a : if and only if they surrounded by a space character.

总之,要替换多次出现的=或a:当且仅当它们被空格字符包围时。

Whichever regex is easier to write.

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

2 个解决方案

#1


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;

#2


1  

Not with javascript... but you get the idea:

不是用javascript ...但你明白了:

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

returns the desired string:

返回所需的字符串:

word another more new: one two

Explanation: the expression / [:=] / finds all "space followed by either colon or equals sign followed by space" and replaces with "space".

说明:表达式/ [:=] /查找所有“空格后跟冒号或等号后​​跟空格”并替换为“空格”。

#1


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;

#2


1  

Not with javascript... but you get the idea:

不是用javascript ...但你明白了:

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

returns the desired string:

返回所需的字符串:

word another more new: one two

Explanation: the expression / [:=] / finds all "space followed by either colon or equals sign followed by space" and replaces with "space".

说明:表达式/ [:=] /查找所有“空格后跟冒号或等号后​​跟空格”并替换为“空格”。