2014-09-10 135 views
0

我有一個xml文件,我需要找到,乘以(例如1.25)並替換所有價格。Notepad ++或PowerGrep正則表達式來查找,乘以和替換價格

價格標籤看起來像這樣: <price><![CDATA[15.9]]></price>

的價格標籤看起來應該在手術後: <price><![CDATA[19.875]]></price>

這可以在記事本中使用正則表達式PowerGrep做++或?

在此先感謝。

+1

正則表達式不能乘以數字。但是你可以編寫一個小程序,它使用正則表達式來查找所有價格,並將其替換並替換。 – trailmax 2014-09-10 13:08:40

回答

0

據我所知,你不能使用任何一個程序來進行數學預處理,但你可以用你選擇的大多數任何語言來構建一個簡單的程序來使用正則表達式來查找數字。將該字符串轉換爲雙精度數字並將其放回到字符串中。今天晚些時候,我可能會用c#構建一些東西,但在大多數語言中它應該是相對直接的。如果您不在Windows環境中,或者使用Powershell for Windows,您甚至可以構建shell腳本並使用grep,但我對Powershell的經驗不足。

編輯:有一個更簡單的方法來做到這一點http://msdn.microsoft.com/en-us/library/hcebdtae(v=vs.110).aspx 這實際上是你想要做的使用xmldocument對象。

編輯2:即使我無法抓住原始海報,我也這樣做了我以爲有人可能會使用這些信息,我學到了很多東西。如果有人感興趣,我可以將源代碼添加到github。

public static void ChangePricesWork(string filepath, double multiply) 
{ 
    var document = new XmlDocument(); 
    document.Load(filepath); 
    XmlNodeList nodeList = document.GetElementsByTagName("price"); 

    foreach (XmlNode node in nodeList) 
    { 
     if (!string.IsNullOrEmpty(node.InnerText)) 
     { 
     node.InnerText = Convert.ToString(multiplyPrice(multiply, node.InnerText)); 
     } 

    } 

    string newFilePath = string.Format(@"{0}\{1}_updated.xml", Path.GetDirectoryName(filepath), Path.GetFileNameWithoutExtension(filepath)); 
    document.Save(newFilePath); 
} 

    private static double multiplyPrice(double multiply, string oldPrice) 
    { 
    var newPrice = new double(); 
    if (Double.TryParse(oldPrice, out newPrice)) 
    { 
     newPrice = newPrice * multiply; 
    } 
    return newPrice; 
    } 
+0

謝謝你,爲了節省我的時間(這將花費在搜索)。對於像你這樣的程序員來說,這可能是一件容易的事情,但對於像我這樣的「用戶」來說,這是一座山。如果(並且只有)它不是什麼大事,我希望看到你說的解決方案。最好的問候。 – Sophocles 2014-09-11 04:55:22

+0

你需要檢查多少個文件,乘以多少?每次都一樣嗎?如果我得到更多信息,我一定會爲你做這件事,這不應該讓我花太多時間,當我不工作時我只需要照顧它。 – thekidxp 2014-09-11 13:10:04

+0

它只有一個文件(xml產品目錄),價格需要乘以1.05(5%的保證金)。 – Sophocles 2014-09-11 14:40:18

0

記事本++有一個Pythonscript插件,允許您創建訪問您的文件,記事本++本身快速的Python腳本。

安裝和設置在this answer中描述。

從那時起,API已經稍微移動了一下,現在您可以用Editor.rereplace替換正則表達式。

# Start a sequence of actions that is undone and redone as a unit. May be nested. 
editor.beginUndoAction() 

# multiply_price_cdata 
from decimal import * 
TWOPLACES = Decimal(10) ** -2 

def multiply_price_cdata(m): 
    price = Decimal(m.group(2)) * Decimal(1.25) 
    return m.group(1) + str(price.quantize(TWOPLACES)) + m.group(3) 

def cdata(m): 
    return "CDATA" 

# npp++ search/replace 
re_price = r'(<price><!\[CDATA\[)(\d+\.\d+|\d+)(\]\]></price>)' 
editor.rereplace(re_price , multiply_price_cdata) 

# end the undo sequence 
editor.endUndoAction() 
+0

當價格具有十進制值時,該腳本正常工作,例如「15.25」,但它不會影響價格,例如沒有小數值,例如「15」。有兩種方法可以增加這兩種類型嗎? – Sophocles 2015-01-03 08:21:29

+0

是的,你可以用'?'指定正則表達式的可選匹配,或者用管道'|'添加邏輯或。我更新了答案以匹配這兩種類型。您也可以使用\ d {2} – Matt 2015-01-03 14:31:42

+0

Thanx指定兩位小數;它似乎很好。 – Sophocles 2015-01-04 10:06:55