I have a variable called line
that can contain something like this with adj or n or adv always appearing first:
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?
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
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:
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
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 "";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.