我有一个xml文件,我需要找到,乘以(例如,乘以1.25),并替换所有价格。
价格标签是这样的:<price><![CDATA[15.9]]></price>
操作后的价格标签应该是这样的:<price><![CDATA[19.875]]></price>
在Notepad++或PowerGrep中使用正则表达式可以做到这一点吗?
提前谢谢。
发布于 2014-09-10 21:09:51
据我所知,您不能使用这两个程序中的任何一个来预演数学,但是您可以使用您选择的几乎任何语言构建一个简单的程序来获取文件,使用正则表达式来查找数字。将该字符串转换为双精度型,进行数学运算,然后将其放回字符串中。今天晚些时候,我可能会用c#构建一些东西,但在大多数语言中应该是相对简单的。如果您不在windows环境中,您甚至可以构建shell脚本并使用grep,或者使用Powershell for windows,但我使用Powershell的经验较少。
编辑:有一种更简单的方法来完成这项工作,这实际上就是您希望使用http://msdn.microsoft.com/en-us/library/hcebdtae(v=vs.110).aspx对象完成的工作。
Edit2:我这样做了,尽管我拿不到原始海报,但我认为有人可能会使用这些信息,我学到了很多。如果有人感兴趣,我可以将源代码添加到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;
}发布于 2014-09-13 02:45:19
Notepad++有一个Pythonscript插件,允许你快速创建可以访问你的文档和Notepad++本身的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()https://stackoverflow.com/questions/25766168
复制相似问题