簡體   English   中英

如何從字符串中獲取這些值?

[英]How do I get these values from a string?

webservice返回以下字符串

“ID:xxxx狀態:yyyy”

如何在沒有“ID:”文本的情況下獲取值ID值,如果沒有“Status:”文本,則獲取“Status”值。

Id值應為xxxx狀態值應為yyyy

值長度未知。

一種方法是使用正則表達式。

這樣做的好處是“自然地”驗證Web服務返回的字符串是否符合您預期的格式,從而可以輕松處理錯誤的輸入。

例如:

Regex regex = new Regex(@"^ID:\s*(.+)\s*Status:\s*(.+)$");
Match match = regex.Match(input);

// If the input doesn't match the expected format..
if (!match.Success)
    throw new ArgumentException("...");

string id = match.Groups[1].Value; // Group 0 is the whole match
string status = match.Groups[2].Value;

^         Start of string
ID:       Verbatim text
\s*       0 or more whitespaces
(.+)      'ID' group (you can use a named group if you like)
\s*       0 or more whitespaces
Status:   Verbatim text
\s*       0 or more whitespaces
(.+)      'Status' group
$         End of string

如果你能澄清xxxxyyyy可以是什么(字母,數字等),我們可能能夠提供更強大的正則表達式。

使用這樣的東西:

string s = "ID: xxxx Status: yyyy";
string[] words = s.Split(' ');
string id = s[1];
string status = s[3];

您可以根據需要將值轉換/轉換為其他數據類型。

暫無
暫無

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

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