2011-05-29 55 views
0

我想用正則表達式替換字符串中的空格。所討論的空間是字符串中兩個元素之間唯一的空間。然而,字符串本身包含更多的元素和空間。到目前爲止,我已經嘗試過替換特定元素之間的特定字符

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

但是這不起作用。它應該採取

< -word anotherword->

,並讓我代替它的空間。

作爲\ S選擇所有空間,以及

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

選擇其間的所有<字符 - 和 - >,我試圖重新使用的表達,但隨後只爲空格。

我不太擅長這些表情,我無法爲我的生活在任何地方找到答案。

如果任何人都能指出我的答案,那就太好了。謝謝。

+0

不清楚的問題,沒有樣本數據,沒有解釋爲「但那樣做nt work「... – 2011-05-29 16:08:25

+0

不知道你有什麼資格作爲非限定元素(」字符串本身包含更多的元素和空間「),我們只能猜測。這些「更多元素」與劃分元素「<-' and '->」有何不同?如果您要顯示包含分隔符和非分隔元素的示例字符串,可能會有所幫助。 – 2011-05-29 16:24:05

+0

嗯,元素主要是文本,並且<- and ->絕不會出現,其中有兩個以上的單詞。他們也總是在同一條線上。 – Lg102 2011-05-29 16:29:53

回答

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

這正是我所期待的,謝謝!太好了,你提供了兩個選項,就像你一樣。 – Lg102 2011-05-30 07:47:33