我有一个名为line
的变量,它可以包含这样的东西,其中adj或n或者adv总是首先出现:
adj 1: text
n 1: any string
adv 1: anything can be here
如何将这些更改为:
j 1: text
n 1: any string
v 1: anything can be here
" adj"," adv"和" n"出现在一行的开头,但在它们之前可以有任意数量的空格?
答案 0 :(得分:2)
您可以尝试使用正则表达式:
//TODO: implement all substitution required here
// if you have few words to substitute "if/else" or "switch/case" will do;
// if you have a lot words have a look at Dictionary<String, String>
private static string Substitute(String value) {
if ("adv".Equals(value, StringComparison.InvariantCultureIgnoreCase))
return "v";
else if ("adj".Equals(value, StringComparison.InvariantCultureIgnoreCase))
return "j";
return value;
}
...
String source = @" adv 1: anything can be here";
String result = Regex.Replace(source, @"(?<=^\s*)[a-z]+(?=\s+[0-9]+:)",
match => Substitute(match.Value));
// " v 1: anything can be here"
Console.Write(result);
答案 1 :(得分:0)
如果它是一个不同的字符串
,则处理上述输入 string line = " adj 1: text ";
line = line.TrimStart(' ');
if (line.StartsWith("adj"))
{
line = line.Remove(0, 3);
line = "j" + line;
}
else if (line.StartsWith("adv"))
{
line = line.Remove(0, 3);
line = "v" + line;
}
// line == "j 1: text "
line = line.Trim();
// line == "j 1: text"
如果您输入的是一个字符串,那么我会先根据Guffa&{39} answer here
分隔换行符string[] lines = theText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
然后跟进已经提到的解决方案。
答案 2 :(得分:0)
类似的事情?
string line = "adj 1: text ";
string newLine = line.Replace("adj","j")
reg选项:
string source = "adv 3: bla bla adj";
Regex regex = new Regex(@"^(adj [0-9]) || ^(adv [0-9])");
Match match = regex.Match(source);
if (match.Success)
{
if (source.Substring(0, 3).Equals("adj"))
source = "j " + source.Substring(3, source.Length - 3);
else
source = "v " + source.Substring(3, source.Length - 3);
}
<强>输出:强>
v 3:bla bla adj
答案 3 :(得分:0)
尝试这样的事情
string ParseString(string Text)
{
Regex re = new Regex(@"\d+");
Match m = re.Match(Text);
if (m.Success && m.Index > 1)
{
return Text.Substring(m.Index - 2);
}
return "";
}