简体   繁体   English

正则表达式匹配字符串

[英]Regex to match string

I have array of strings with following data: 我有以下数据的字符串数组:

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

Positions marked with '' are strings rest is double, I need help with regex to get only strings. 标有''的位置是字符串其余部分是双的,我需要正则表达式帮助才能只获得字符串。

Why do you need regex for this? 为什么为此需要正则表达式?

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

this accepts the decimal separator of the current culture. 这接受当前区域性的小数点分隔符。 You can change it if you use the overload of double.TryParse . 如果使用double.TryParse的重载,则可以更改它。 It seems to be , for you as your sample data suggests. 正如您的样本数据所暗示的那样,对您来说似乎是。

If you want to allow point as decimal separator: 如果要允许点作为小数点分隔符:

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

If the non-doubles really start all with ' you could also make it simpler: 如果非双打全以'开头,那么您也可以使其更简单:

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

the String 's StartsWith EndsWith methods should do the trick: 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 one-liner: LINQ单线:

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

Or, if you want to strip the quotes: 或者,如果要删除引号:

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