[英]How can I change the value of the first word in a line with C#
I have a variable called line
that can contain something like this with adj or n or adv always appearing first: 我有一个名为line
的变量,该变量可以包含总是带有adj或n或adv这样的内容:
adj 1: text
n 1: any string
adv 1: anything can be here
How can I change these to be: 我如何将它们更改为:
j 1: text
n 1: any string
v 1: anything can be here
Where the "adj", "adv" and "n" appear at the start of a line but can have any number of spaces before them? “ adj”,“ adv”和“ n”出现在行的开头,但它们前面可以有任意空格吗?
You can try using regular expressions : 您可以尝试使用正则表达式 :
//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);
This deals with the above mentioned input if it's all a different string 如果都是不同的字符串,则处理上述输入
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"
If your input is one string then I would first split it on line break as per Guffa 's answer here 如果您输入的是一个字符串,那么我将首先按照Guffa的答案在 换行符上将其拆分
string[] lines = theText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
and then follow up with the already mentioned solution. 然后执行已经提到的解决方案。
something like that ?? 那样的东西??
string line = "adj 1: text ";
string newLine = line.Replace("adj","j")
reg option: 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);
}
output: 输出:
v 3: bla bla adj v 3:bla bla adj
Try something like this 试试这个
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.