开发者

replacing specific characters in between specific elements

I'd like to use a regular expression 开发者_如何学编程to replace a space in a string. The space in question is the only space between two elements in the string. The string itself however contains much more elements and spaces. So far i've tried

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

But that doesnt work. It is supposed to take

<-word anotherword->

and allow me to replace the space in it.

As \s selects all spaces, and

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

Selects all characters inbetween the <- and ->, i tried to re-use the expression but then for the spaces only.

I'm not so good at these expressions, and i can't for the life of me find an answer anywhere.

If anyone could just point me to the answer, that would be great. Thanks.


It's difficult to be sure what you want, post some before and after examples. And, specify what language you are using.

But, it looks like (<-\S+)\s*(\S+->) should probably do it (deletes spaces).

If the <- and -> are NOT to be preserved, move them out of the parentheses, like so:
<-(\S+)\s*(\S+)->

Here's what it would look like in 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);

Which yields:

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->.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜