簡體   English   中英

使用正則表達式從字符串中提取值

[英]extract a value from a string using regex

我正在嘗試使用正則表達式從字符串中提取值。 該字符串如下所示:

<faultcode>&lt;![CDATA[900015The new password is not long enough. PasswordMinimumLength is 6.]]&gt;</faultcode>

我正在嘗試僅將錯誤消息顯示給最終用戶。

由於您可能想要所有<![CDATA[]]>因此應該適合:

<!\[CDATA\[(.+?)\]\]>

唯一明智的做法是將其加載到XElement (或XDocument,XmlDocument)中,並從CDATA元素中提取Value。

XElement e = XElement.Parse(xmlSnippet);
string rawMsg = (e.FirstNode as XCData).Value;
string msg = rawMsg.Substring("900015".Length);

更新為與問題編輯相對應:

var xml = XElement.Parse(yourString);
var allText = xml.Value;
var stripLeadingNumbers = Regex.Match(xml.Value, @"^\d*(.*)").Groups[1].Value;

首先,最重要的是,使用regex解析XML / HTML是不好的

現在,通過錯誤消息,我認為您的意思是文本,不包括數字。 像這樣的表達式可能會解決問題:

\<([^>]+)\>&lt;!\[CDATA\[\d*(.*)\]\]&gt;\</\1\>

錯誤消息將在第二組中。 這將與您提供的示例一起使用,但是我將盡快使用XDocumentXmlDocument進行解析。 如果使用的是C#,則確實沒有充分的理由不使用這兩個類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM