2012-07-19 72 views
0

的重复我有一个这样的字符串中的模式:正则表达式来清洁字符

T T,我想T

,它可以从[a-z]是任何字符。

我试过这个Regex Example但无法取代它。

编辑

像我有A Aa ar r,那么它应该成为Aar手段代替任何字符第一或第二,不管它是什么。

+2

我不太明白这里的要求。你必须由一个空格分隔的字符,你只需要第一个?还是第二?你使用哪种语言?你不需要这个正则表达式。 – 2012-07-19 12:56:24

+3

我认为你需要再试一次 - 你的问题是非感性的 – BonyT 2012-07-19 12:56:37

+0

我在问题中发布的链接中添加了模式..我使用'c#' – user1530755 2012-07-19 12:57:54

回答

1

您可以使用此反向引用。

/([a-z])\s*\1\s?/gi 

Example

一些更多的解释:

(   begin matching group 1 
    [a-z] match any character from a to z 
)   end matching group 1 
\s*   match any amount of space characters 
\1   match the result of matching group 1 
      exactly as it was again 
      this allows for the repition 
\s?   match none or one space character 
      this will allow to remove multiple 
      spaces when replacing 
+0

你能告诉我什么是'\ 1'的含义.. ?? – user1530755 2012-07-19 13:24:10

+0

这意味着正则表达式试图再次复制第一个匹配组的完全相同的结果。 因此,说'([a-z])'匹配'A' - 那么'\ 1'会尝试完全匹配'A'等等。 如果您有多个匹配组,例如'([a-z])([0-9])',你可以使用'\ 1','\ 2'等反向引用这些组的结果。 – 2012-07-19 13:40:35

+0

我添加了一个显示替换及其工作原理的示例。 – 2012-07-19 13:46:19