简体   繁体   中英

Get specific string after specific character

I have a few string:

  1. <img title=\"\\angle X &lt; \\angle Y &lt; \\angle Z\" src=\"http://latex.codecogs.com/gif.latex?\\angle&amp;space;X&amp;space;&lt;&amp;space;\\angle&amp;space;Y&amp;space;&lt;&amp;space;\\angle&amp;space;Z\" />

I want to get angle&amp;space;X&amp;space;&lt;&amp;space;\\angle&amp;space;Y&amp;space;&lt;&amp;space;\\angle&amp;space;Z

and

  1. <img title=\"1,25 - \\frac{5}{6} \\times 280\\% \\div 1\\tfrac{1}{6}\" src=\"http://latex.codecogs.com/gif.latex?1,25&amp;space;-&amp;space;\\frac{5}{6}&amp;space;\\times&amp;space;280\\%&amp;space;\\div&amp;space;1\\tfrac{1}{6}\" />

I want to get:

frac{5}{6}&amp;space;\\times&amp;space;280\\%&amp;space;\\div&amp;space;1\\tfrac{1}{6}

Code:

string imgSoal;
string imgName = imgSoal.Split("\\")[1];

I'm having a problem, ie the string that I got from the above code are angle&amp;space;X&amp;space;&lt;&amp;space; and frac{5}{6}&amp;space; How to get string i want ( angle&amp;space;X&amp;space;&lt;&amp;space;\\angle&amp;space;Y&amp;space;&lt;&amp;space;\\angle&amp;space;Z and frac{5}{6}&amp;space;\\times&amp;space;280\\%&amp;space;\\div&amp;space;1\\tfrac{1}{6} )?

You can use the IndexOf method to get the first occurrence of the \\ (inputChar) and then get the remaining string by using the SubString method.

var result = str.Substring(str.IndexOf(inputChar) + 1);

You need the handle the case if the given character is not present in the given string.

For your requirement, the better way is create Regex to match the string that your want then remove unrelated character. I have implement the follow code please check.

private string stringA = "<img title=\"\\angle X &lt; \\angle Y &lt; \\angle Z\" src=\"http://latex.codecogs.com/gif.latex?\\angle&amp;space;X&amp;space;&lt;&amp;space;\\angle&amp;space;Y&amp;space;&lt;&amp;space;\\angle&amp;space;Z\" />";
private string stringB = "<img title=\"1,25 - \\frac{5}{6} \\times 280\\% \\div 1\\tfrac{1}{6}\" src=\"http://latex.codecogs.com/gif.latex?1,25&amp;space;-&amp;space;\\frac{5}{6}&amp;space;\\times&amp;space;280\\%&amp;space;\\div&amp;space;1\\tfrac{1}{6}\" />";
private string patternA = @"\?(.*?)/>";
private string patternB = @";\\frac(.*?)/>";

foreach (Match match in Regex.Matches(stringA, patternA))
{

    Console.WriteLine(match.Value);
    var tem = match.Value.Remove(0, 2);
    var res = tem.Substring(0, tem.Length - 4);
}
foreach (Match match in Regex.Matches(stringB, patternB))
{

    Console.WriteLine(match.Value);
    var tem = match.Value.Remove(0, 2);
    var res = tem.Substring(0, tem.Length - 4);
}

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.

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