我有以下字符串:獲取特定字符串模式
string str ="dasdsa|cxzc|12|#dsad#|czxc";
我需要返回一個函數:#dsad#
考慮考慮是#dsad#
是動態創建的,因此可能會有所不同,它的長度也可以改變
如何使用正則表達式(搜索兩個哈希標籤之間的字符串)或其他方法(如果可用)來執行此操作?
我有以下字符串:獲取特定字符串模式
string str ="dasdsa|cxzc|12|#dsad#|czxc";
我需要返回一個函數:#dsad#
考慮考慮是#dsad#
是動態創建的,因此可能會有所不同,它的長度也可以改變
如何使用正則表達式(搜索兩個哈希標籤之間的字符串)或其他方法(如果可用)來執行此操作?
如果字符串是管道分隔的字符串,可以與|
分裂,並抓住啓動,並與#
結束值。
var str ="dasdsa|cxzc|12|#dsad#|czxc";
var result = str.Split('|').Where(p => p.StartsWith("#") && p.EndsWith("#")).ToList();
foreach (var s in result)
Console.WriteLine(s);
如果你只需要一個值,使用.FirstOrDefault()
:
var result = str.Split('|')
.Where(p => p.StartsWith("#") && p.EndsWith("#"))
.FirstOrDefault();
就我個人而言,[我更喜歡.NET Fiddle](https://dotnetfiddle.net/wRbLqC)在Ideone上。它感覺更直觀,更快。 –
@UweKeim:是的,它也很棒。我更喜歡在[de gustibus non est disputandum](https://en.wikipedia.org/wiki/De_gustibus_non_est_disputandum)方面。 –
看起來像今天是一個downvoting的日子。 +1給所有回答的人。 –
假設你想匹配上,你可以採取以下的正則表達式#字符:
#[a-z]+#
如果你想讓你的字符串總是爲1 | 2 | 3 |#4#| 5,你可以使用String.Split('|')方法,並且只取第四個結果元素。
今天看起來像是一個低調的日子。 +1給所有回答的人。 –
假設#dasd#
字符串中只出現一次嘗試這個辦法:
String a = "asd|asd|#this#|asdasd";
string m = Regex.Match(a, @"#.+#").Value;
Console.WriteLine(m);
.+
搜索任何字符
如果字符串使用|
作爲分隔符,你也可以拆分字符串。
string [] array = a.Split('|');
// this would get a list off all values with `#`
List<string> found_all = array.Where(x => x.Contains("#")).ToList();
// this would get the first occurrence of that string. If not found it will return null
string found = array.FirstOrDefault(x => x.Contains("#"))
看起來像今天是一個低調的日子。 +1給所有回答的人。 –
根據你需要尋找這兩個主題標籤之間的字符串後面將正則表達式的問題給出的輸入,
^.*#(.*)#.*$
如果數據在2個哈希標籤之間爲空,那麼正則表達式不會失敗。這將需要空值。
今天看起來像是一個低調的日子。 +1給所有回答的人。 –
這似乎是由五部分數據的CSV分隔數據。
提取每個部分,然後使用正則表達式將其投影到動態實體中以表示每個部分。
string data = "dasdsa|cxzc|12|#dsad#|czxc";
string pattern = @"(?<Section1>[^|]+)\|(?<Section2>[^|]+)\|(?<Section3>[^|]+)\|(?<Section4>[^|]+)\|(?<Section5>[^|]+)";
var results =
Regex.Matches(data, pattern, RegexOptions.ExplicitCapture)
.OfType<Match>()
.Select(mt => new
{
One = mt.Groups["Section1"].Value,
Two = mt.Groups["Section2"].Value,
Three = mt.Groups["Section3"].Value,
Four = mt.Groups["Section4"].Value,
Five = mt.Groups["Section5"].Value,
})
.ToList();
Console.WriteLine(results[0].Four); // #dsad#
一旦從results
包含的內容完整提取出來。因爲它只是多行捕獲的列表,其中每行只包含該行的一個數據實體。
從適當的屬性中提取;而我們的最終結果上有一條線,但我們可以得到的數據作爲示例所示WriteLine
:那#DSAD#是動態創建的,因此可能會有所不同
看起來像今天是一個低調的日子。 +1給所有回答的人。 –
「正在考慮以它的長度可也可以改變「你能澄清一下'#dsad#'是什麼,如果可以改變? –
它是一個數據庫值,str是一個cookie中使用的字符串 – Sora
它是一個管道分隔的字符串嗎?用'|'分割,並抓取以'#'開頭和結尾的值。請參閱http://ideone.com/yk34S3 –