Notepad++或PowerGrep正则表达式,用于查找、相乘和替换价格



我有一个xml文件,我需要找到它,乘以(例如1.25)并替换所有价格。

价格标签是这样的:<price><![CDATA[15.9]]></price>

操作后的价格标签应该是这样的:<price><![CDATA[19.875]]></price>

这可以在Notepad++或PowerGrep中使用正则表达式完成吗?

提前谢谢。

据我所知,你不能使用任何一个程序来预处理数学,但你可以用你选择的大多数语言构建一个简单的程序来获取文件,使用正则表达式来查找数字。把那个字符串作为一个double进行数学运算,然后把它放回字符串中。今天晚些时候,我可能会用c#构建一些东西,但在大多数语言中应该是相对直接的。如果你不在windows环境中,或者使用Powershell for windows,你甚至可以构建一个shell脚本并使用grep,但我对Powershell的经验较少。

编辑:有一种更简单的方法http://msdn.microsoft.com/en-us/library/hcebdtae(v=vs.110).aspx这基本上就是您想要使用xmldocument对象执行的操作。

第二版:我这样做了,尽管我拿不到原始海报,我想有人可能会使用这些信息,我学到了很多。如果有人感兴趣,我可以将源代码添加到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;
   }

Notepad++有一个Pythonscript插件,允许您创建可以访问文档和Notepad++本身的快速Python脚本。

此答案中介绍了安装和设置。

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()

最新更新