2011-03-01 117 views
2
分離點

我使用不會直接支持我的表/字段參數語法的C#表達文庫:正則表達式來查找公式

以下是不直接支持表/字段參數名:

TableName1.FieldName1 
[TableName1].[FieldName1] 
[Table Name 1].[Field Name 1] 

它接受不帶空格的字母數字參數或大括號括在方括號內。我想用C#正則表達式替換點分離器和鄰近支架到不同的分隔符,那麼結果將是如下:

[TableName1|FieldName1] 
[TableName1|FieldName1] 
[Table Name 1|Field Name 1] 

我還需要單引號內跳過任何字符串文字,如:

'TableName1.FieldName1' 

,當然,忽略任何數字文字,如:

12345.6789 

編輯:感謝您對改善我的問題反饋。希望現在更清楚。

+2

您無法提供足夠的信息。 「隔離」是一個通用的和相對的術語,你不能通過向已經很模糊的條件添加條件來堆砌規範。更具體一些使用背景。 – sln 2011-03-01 02:02:47

+0

我同意,我對你想達到的目標沒有確定的想法。也許你可以說明你想要運行正則表達式的結果,也許還有你不想看到的結果(有時可能真的有用) – iain 2011-03-01 04:00:45

+0

另外,你應該指定你正在使用的正則表達式引擎。有沒有像'[Table.Name]。[Field.Name]'這樣的結構,你只想在中點上分割? – 2011-03-01 07:53:10

回答

2

我寫了一個全新的答案,現在的問題是澄清:

可以在一個單一的正則表達式做到這一點。我想,這是相當防彈的,但正如你所看到的,這不完全是自明性的,這就是爲什麼我自由地評論它的原因。希望它是有道理的。

你很幸運,.NET允許重新使用命名捕獲組,否則你將不得不在幾個步驟中這樣做。

resultString = Regex.Replace(subjectString, 
    @"(?:    # Either match... 
    (?<before>  # (and capture into backref <before>) 
     (?=\w*\p{L}) # (as long as it contains at least one letter): 
     \w+    # one or more alphanumeric characters, 
    )    # (End of capturing group <before>). 
    \.    # then a literal dot, 
    (?<after>  # (now capture again, into backref <after>) 
     (?=\w*\p{L}) # (as long as it contains at least one letter): 
     \w+    # one or more alphanumeric characters. 
    )    # (End of capturing group <after>) and end of match. 
    |     # Or: 
    \[    # Match a literal [ 
    (?<before>  # (now capture into backref <before>) 
     [^\]]+   # one or more characters except ] 
    )    # (End of capturing group <before>). 
    \]\.\[   # Match literal ].[ 
    (?<after>  # (capture into backref <after>) 
     [^\]]+   # one or more characters except ] 
    )    # (End of capturing group <after>). 
    \]    # Match a literal ] 
    )     # End of alternation. The match is now finished, but 
    (?=    # only if the rest of the line matches either... 
    [^']*$   # only non-quote characters 
    |    # or 
    [^']*'[^']*'  # contains an even number of quote characters 
    [^']*   # plus any number of non-quote characters 
    $    # until the end of the line. 
    )     # End of the lookahead assertion.", 
    "[${before}|${after}]", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace); 
+0

這是完美的,正是我所需要的。我非常感謝所有解釋它如何工作的評論。希望這會對其他嘗試學習正則表達式的人有所幫助。謝謝你的幫助Tim。 – polara 2011-03-02 18:24:03

-1

希望你可以試試這個正則表達式:/(\w[0-9]* *)+/g這個過濾掉所有的字母數字除了。

+0

對不起,但這是相當荒謬的。它與OP給出的例子都不匹配,但它確實匹配唯一編號的反例。當然,它根本不在乎引用的字符串...... – 2011-03-02 07:38:08