0

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?

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

4 Answers4

2

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);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

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.

Community
  • 1
  • 1
pijemcolu
  • 2,257
  • 22
  • 36
0

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

Leon Barkan
  • 2,676
  • 2
  • 19
  • 43
0

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 "";
}
askeet
  • 689
  • 1
  • 11
  • 24