我想用一個正則表達式找到16位號碼的父節點,並返回整節,但不能弄清楚如何,所以給出:如何獲得正則表達式的工作?
<Details>
<CreditCard cardnum="123456789" ccv="123" exp="0212" cardType="1" name="joe" />
</Details>
我要回:
<CreditCard cardnum="123456789" ccv="123" exp="0212" cardType="1" name="joe" />
然後,我將使用解析xml並獲取每個屬性是一個數字並將其刪除。
我試過.*(\d{13,16}).*
,但是這會得到每個角色。
一次,我做的:
XElement element = XElement.Parse(xml); // XDocument.Load(xmlFile).Root
IEnumerable<XElement> elementsWithPossibleCCNumbers =
element.Descendants()
.Where(d => d.Attributes()
.Where(a => a.Value.Length == 16)
.Count() == 1);
我想不通通過elementsWithPossibleCCNumbers每個屬性如何循環,例如:
foreach(var x in elementsWithPossibleCCNumbers)
{
//If attribute is number, replace value with empty string
}
注:我刪除了int.TryParse爲現在。
我決定這樣做:
IEnumerable<XElement> elementsWithPossibleCCNumbers =
element.Descendants()
.Where(d => d.Attributes()
.Where(a => a.Value.Length >= 13 && a.Value.Length <= 16)
.Count() == 1).Select(x=>x);
foreach(var x in elementsWithPossibleCCNumbers)
{
foreach(var a in x.Attributes())
{
xml = xml.Replace(a.Value, new String('*',12));
}
}
然而,如果我有一個第二元件具有16位數字的屬性,它只替換的屬性值的一部分。
當談到正則表達式我平時靠禱告,咒罵,和魔術才能正常工作。 – Yuck 2012-02-01 16:03:53
爲什麼不反序列化XML?或者使用LINQ to XML來準確地返回你需要的XML元素? – 2012-02-01 16:03:55
如果你不想反序列化你也可以看看使用XPath。 – seanzi 2012-02-01 16:04:47