2011-11-13 50 views
1

我想解析一些C#代碼到Python。該代碼中有幾個正則表達式。一切運行良好,到目前爲止,但現在我已經得到了以下問題:等效於Python中的C#matchObject.Value?

C#代碼:

Match m = regEx.Match(Expression); 
while(m.Success) 
{ 
    Expression = Expression.Replace(m.Value, m.Groups[1].Value + this.Solve(m.Groups[2].Value)); 
} 

我能做些什麼,使這個代碼在python的工作?我已經試過這樣的事情:

matchObj = re.search(pattern = p, string = expression, flags = re.IGNORECASE) 
while matchObj: 
    if len(matchObj.group(3)) > 0: 
     expression = re.sub(pattern = p, repl = matchObj.group(1) + self.solve(matchObj.group(2)), string = matchObj.string, flags = re.IGNORECASE) #Here is the problem... 

所以實際上我正在尋找相當於matchObject.Value的東西。

謝謝你的幫助。

回答

1

我認爲這是你想要做的; match.group()(不帶參數)返回匹配整個正則表達式匹配:

m = re.search(pattern, text) 
if m and len(m.group(3)) > 3: 
    text = text.replace(m.group(), m.group(1) + solve(m.group(2))) 

我不知道爲什麼你有一個循環那裏,所以我刪除它。另一種方式,不使用str.replace將根據m.start()m.end()返回的位置來操作字符串。

+0

就是這樣。調試完C#代碼和Python代碼後,我可以自己找到它。感謝您的回答。 – oopbase

0

那麼,re.search會在Python中返回Match對象。從文檔:

掃描字符串查找此正則表達式生成匹配的位置,並返回相應的MatchObject實例。如果字符串中沒有位置與模式匹配,則返回None;請注意,這與在字符串中的某處找到零長度匹配不同。

要從python MatchObject獲取整個匹配的字符串,請使用group方法。 matchObj.group()matchObj.group(0)將返回整個匹配的字符串,而matchObj.group(1)將返回第一個匹配的組,等等。這與C#的匹配非常相似。

現在,關於您的C#代碼...是不是一個無限的while循環呢? m.Success將永遠返回truem.Value將始終給你相同的結果。 Match方法只匹配正則表達式的第一個匹配項。您是否想要使用Matches方法,該方法返回MatchCollection?或者您在替換中調用的Solve方法實際上是否更新了m的值?