替换特定元素之间的特定字符

时间:2011-05-29 15:43:49

标签: regex spaces

我想使用正则表达式替换字符串中的空格。有问题的空间是字符串中两个元素之间的唯一空格。然而,字符串本身包含更多的元素和空格。到目前为止我已经尝试了

(<-)[\s]*?(->)

但那不起作用。它应该采取

&lt; -word anotherword-&gt;

并允许我替换其中的空格。

当\ s选择所有空格时,

(<-)[\s\S]*?(->)

选择&lt; - 和 - &gt;之间的所有字符,我试图重复使用表达式,但仅用于空格。

我对这些表达方式并不擅长,而且我无法在任何地方找到答案。

如果有人能指出我的答案,那就太好了。感谢。

1 个答案:

答案 0 :(得分:0)

很难确定你想要什么,在示例之前和之后发布一些内容。并且,指定您正在使用的语言。

但是,看起来(<-\S+)\s*(\S+->)应该这样做(删除空格)。

如果不保留<-->,请将它们移出括号,如下所示:
<-(\S+)\s*(\S+)->

这是JavaScript中的样子:

var before  = "Ten years ago a crack <-flegan esque-> unit was sent to prison by a military "
            + "court for a crime they didn't commit.\n"
            + "These men promptly escaped from a maximum security stockade to the "
            + "<-flargon 666-> underground.\n"
            + "Today, still wanted by the government, they survive as soldiers of fortune.\n"
            + "If you have a problem and no one else can help, and if you can find them, "
            + "maybe you can hire the <-flugen  9->.\n"
            ;

var after   = before.replace (/(<-\S+)\s*(\S+->)/g, "$1$2");

alert (after);

哪个收益率:

Ten years ago a crack <-fleganesque-> unit was sent to prison by a military court for a crime they didn't commit.
These men promptly escaped from a maximum security stockade to the <-flargon666-> underground.
Today, still wanted by the government, they survive as soldiers of fortune.
If you have a problem and no one else can help, and if you can find them, maybe you can hire the <-flugen9->.