繁体   English   中英

如何使用C#更改一行中第一个单词的值

[英]How can I change the value of the first word in a line with C#

我有一个名为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”出现在行的开头,但它们前面可以有任意空格吗?

您可以尝试使用正则表达式

//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);

如果都是不同的字符串,则处理上述输入

    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答案在 换行符上将其拆分

string[] lines = theText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);

然后执行已经提到的解决方案。

那样的东西??

   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

试试这个

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 "";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM