簡體   English   中英

正則表達式匹配字符串

[英]Regex to match string

我有以下數據的字符串數組:

'STSO/82465'
'CPB'
550
'B'
'IEC2'
'IEC2'
50
525
680
1550,1175
'500000/V3'
'23585/V3'
''
etc...

標有''的位置是字符串其余部分是雙的,我需要正則表達式幫助才能只獲得字符串。

為什么為此需要正則表達式?

double d;
string[] noDoubles = Array.FindAll(arr, s => !double.TryParse(s, out d));

這接受當前區域性的小數點分隔符。 如果使用double.TryParse的重載,則可以更改它。 正如您的樣本數據所暗示的那樣,對您來說似乎是。

如果要允許點作為小數點分隔符:

Array.FindAll(arr, s => !double.TryParse(s, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out d));

如果非雙打全以'開頭,那么您也可以使其更簡單:

string[] noDoubles = Array.FindAll(arr, s => s.StartsWith("'"));

StringStartsWith EndsWith方法應該可以解決問題:

var tab = new[]
        {
            "'STSO/82465'",
            "'CPB'",
            "550",
            "'B'",
            "'IEC2'",
            "'IEC2'",
            "50",
            "525",
            "680",
            "1550,1175",
            "'500000/V3'",
            "'23585/V3'"
        };
        foreach (var s in tab)
        {
            if (s.StartsWith("'") && s.EndsWith("'"))
            {
                //use the s
            }
        }

LINQ單線:

var linesWithStrings = allLines.Where( l => l.StartsWith( "'" ) );

或者,如果要刪除引號:

var linesWithStrings = from s in allLines
                       where s.Length >= 2 && s.StartsWith( "'" ) && s.EndsWith( "'" )
                       select s.Substring( 1, s.Length - 2 );

暫無
暫無

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

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