在C#中使用Linq拆分具有不同条件的字符串

ven*_*kat -3 c# linq c#-4.0

我需要从字符串中提取和删除一个单词.字应该是大写,和之后的定界符之一/,;,(,-或的空间.

一些例子:

  1. "this is test A/ABC"
    预期产出:"this is test A""ABC"

  2. "this is a test; ABC/XYZ"
    预期产出:"this is a test; ABC""XYZ"

  3. "This TASK is assigned to ANIL/SHAM in our project"
    预期产出:"This TASK is assigned to ANIL in our project""SHAM"

  4. "This TASK is assigned to ANIL/SHAM in OUR project"
    预期产出:"This TASK is assigned to ANIL/SHAM in project""OUR"

  5. "this is test AWN.A"
    预期产出:"this is test""AWN.A"

  6. "XETRA-DAX" 预期产出:"XETRA""DAX"

  7. "FTSE-100" 预期产出:"-100""FTSE"

  8. "ATHEX" 预期产出:"""ATHEX"

  9. "Euro-Stoxx-50" 预期产出:"Euro-Stoxx-50"""

我怎样才能做到这一点?

xan*_*tos 14

"智能"版本:

    string strValue = "this is test A/ABC";
    int ix = strValue.LastIndexOfAny(new[] { '/', ' ', ';', '(', '-' });
    var str1 = strValue.Substring(0, ix);
    var str2 = strValue.Substring(ix + 1);
Run Code Online (Sandbox Code Playgroud)

一个"愚蠢的LINQ"版本:

    var str3 = new string(strValue.Reverse().SkipWhile(p => p != '/' && p != ' ' && p != ';' && p != '(' && p != '-').Skip(1).Reverse().ToArray());
    var str4 = new string(strValue.Reverse().TakeWhile(p => p != '/' && p != ' ' && p != ';' && p != '(' && p != '-').Reverse().ToArray());
Run Code Online (Sandbox Code Playgroud)

两种情况都没有检查.OP可以添加支票,如果他想要的话.

对于第二个问题,使用LINQ真的太难了.使用正则表达式,它"很容易".

var regex = new Regex("^(.*[A-Z]+)([-/ ;(]+)([A-Z]+)(.*?)$");

var strValueWithout = regex.Replace(strValue, "$1$4");
var extractedPart = regex.Replace(strValue, "$3");
Run Code Online (Sandbox Code Playgroud)

对于第三个问题

var regex = new Regex("^(.*?)([A-Z.]*)([-/ ;(]+)([A-Z.]+)(.*?)$", RegexOptions.RightToLeft);

var strValueWithout = regex.Replace(strValue, "$1$2$5");
var extractedPart = regex.Replace(strValue, "$4");
Run Code Online (Sandbox Code Playgroud)

使用代码示例:http://ideone.com/5OSs0

另一个更新(它变成了BORING)

Regex Regex = new Regex(@"^(?<1>.*?)(?<2>[-/ ;(]*)(?<=\b)(?<3>[A-Z.]+)(?=\b)(?<4>.*?)$|^(?<1>.*)$", RegexOptions.RightToLeft);
Regex Regex2 = new Regex(@"^(?<1>.*?)(?<2>[-/ ;(]*)(?<=\b)(?<3>(?:\p{Lu}|\.)+)(?=\b)(?<4>.*?)$|^(?<1>.*)$", RegexOptions.RightToLeft);

var str1 = Regex.Replace(str, "$1$4");
var str2 = Regex.Replace(str, "$3");
Run Code Online (Sandbox Code Playgroud)

两者之间的区别在于,第一个将使用AZ作为大写字符,第二个将使用其他"大写"字符,例如 ÀÈÉÌÒÙ

使用代码示例:http://ideone.com/FqcmY

  • @sukumar你应该学会提出更好的问题,在你的所有帖子中你都不要提到你需要拆分并提取大写单词的"夫妻". (5认同)

Kob*_*obi 6

这应该根据新的要求工作:它应该找到用大写单词包装的最后一个分隔符:

Match lastSeparator = Regex.Match(strExample,
                                  @"(?<=\b\p{Lu}+)[-/ ;(](\p{Lu}+)\b",
                                  RegexOptions.RightToLeft); // last match
string main = lastSeparator.Result("$`$'");  // before and after the match
string word = lastSeparator.Groups[1].Value; // word after the separator
Run Code Online (Sandbox Code Playgroud)

这个正则表达式有点棘手.主要技巧:


工作示例:http://ideone.com/U9AdK