我有以下字符串
$(tput cols)
我想从该字符串中获取%*s
个字词
有些只有"$2"
,有些只有string test = "viv-ek is a good boy.Mah - esh is Cra - zy.";
。
答案 0 :(得分:0)
您可以使用以下正则表达式找到您的字词:
\b\w+(?:\s-\s|-)\w+\b
并将带有(?:\s-\s|-)
的匹配字符串的结果替换为空字符串''
。
答案 1 :(得分:0)
答案 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”的列表。
替换单词的方式相同:
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.