2012-07-16 50 views
0

替換MatchCollection項我有一個包含像數學表達式的字符串:從字符串

strExpression= a+b+tan(a)+tan(b)+a+b 

我想與a和b(比如說A = 10,B = 20),以使得值替換該表達式它成爲:

10+20+tan(10)+tan(20)+10+20 

但是當我使用Regex.Replace我得到:

10+20+t10n(10)+t10n(20)+10+20 

我怎麼能代替的和b的值位於C直立的地方。

我已經filterd了包含MatchCollection對象:

{a},{b},{tan},{a},{tan},{b},{a},{b} 
+1

你能告訴我們你已經嘗試了正則表達式? – Shai 2012-07-16 05:40:53

回答

1

您可以使用單詞邊界\b之前和變量名後(如\ba\b可變a\bb\b可變b)在變量匹配表達。

0
string expression = "strExpression= a+b+tan(a)+tan(b)+a+b"; 
expression = Regex.Replace(expression, @"\ba\b", "10"); 
expression = Regex.Replace(expression, @"\bb\b", "20"); 
Console.WriteLine(expression); 
0

儘量在你的正則表達式更具體的,而不是僅僅更換值。這裏是描述捕捉到的字符是否是可變的一些規則或不

  1. 變量必須具有二元運算符(+, - ,*,/)和optinally空間在它的右邊(如果啓動),在它的左邊(如果結束)還是兩側。如果通過功能它也可以在它周圍有paranethis。 因此,創建滿足所有這些條件
0

你可以用這個做一個正則表達式:

Regex Example

然後用同樣的方法爲b與更換20

1

使用邊界\b

\b The match must occur on a boundary 
     between a \w (alphanumeric) and a \W (nonalphanumeric) character. 

例如:

\b\w+\s\w+\b 

結果是

"them theme" "them them" in "them theme them them" 

,這樣使用:

Regex.Replace(inputString, @"(\bb\b)", "20"); 
Regex.Replace(inputString, @"(\ba\b)", "10"); 
+0

感謝它的工作.. – 2012-07-16 06:18:55

+0

@ user1527958:已解決的問題? – Ria 2012-07-16 06:21:32