包含特殊字符的子字符串特定字

时间:2016-01-28 06:50:59

标签: c# regex string substring match

我有以下字符串

$(tput cols)

我想从该字符串中获取%*s个字词

有些只有"$2",有些只有string test = "viv-ek is a good boy.Mah - esh is Cra - zy.";

4 个答案:

答案 0 :(得分:0)

您可以使用以下正则表达式找到您的字词:

\b\w+(?:\s-\s|-)\w+\b

并将带有(?:\s-\s|-)的匹配字符串的结果替换为空字符串''

答案 1 :(得分:0)

\b\w+\s*-\s*\w+\b

你可以尝试一下。参见演示。

https://regex101.com/r/cZ0sD2/14

答案 2 :(得分:0)

这可能会为你做到这一点

string test = "viv-ek is a good boy.Mah - esh is Cra - zy.";
test = test.Replace(" -", "-").Replace("- ", "-").Replace(".", ". ");
//Or
//test = test.Replace(" - ", "-").Replace(".", ". ");
string[] allwords = test.Split(' ');
List<string> extractedWords=new List<string>();
foreach(string wrd in allwords)
{
    if(wrd.Contains("-"))
    {
        extractedWords.Add(wrd.Replace("-", ""));
    }
}

答案 3 :(得分:0)

如果您只想选择这些单词,请使用:

string test = "viv-ek is a good boy.Mah - esh is Cra - zy.";
var words = 
    Regex
        .Matches(test, @"(?<part>\w+)(\s*-\s*(?<part>\w+))+\b")
        .Cast<Match>()
        .Select(
            x => string.Join(
                string.Empty, 
                x.Groups["part"].Captures.Cast<Capture>().SelectMany(capture => capture.Value)))
        .ToList();

words是一个包含“vivek”,“Mahesh”,“Crazy”的列表。

DEMO

替换单词的方式相同:

var replacingValues = new Dictionary<string, string> { { "Crazy", "XXX" } };
var test = "viv-ek is a good boy.Mah - esh is Cra - zy.";
var replacedTest =
    Regex.Replace(
        test,
        @"\b(?<part>\w+)(\s*-\s*(?<part>\w+))+\b",
        match =>
            {
                var word = string.Join(string.Empty, match.Groups["part"].Captures.Cast<Capture>().SelectMany(capture => capture.Value));
                string replacingValue;
                return replacingValues.TryGetValue(word, out replacingValue) ? replacingValue : match.Value;
            });

replacedTest包含viv-ek is a good boy.Mah - esh is XXX.

DEMO