1

I'am creating my own forum. I've got problem with quoting messages. I know how to add quoting message into text box, but i cannot figure out how to extract values from string after post. In text box i've got something like this:

[quote IdPost=8] Some quoting text [/quote]

[quote IdPost=15] Second quoting text [/quote]

Could You tell what is the easiest way to extract all "IdPost" numbers from string after posting form ?.

3
  • Do you want the number on [quote] or the string between [quote][/quote] ? Commented Dec 16, 2014 at 22:24
  • Numbers. I will handle with the rest. Commented Dec 16, 2014 at 22:26
  • Ok I will edit my answer. Commented Dec 16, 2014 at 22:36

3 Answers 3

5

by using a regex

@"\[quote IdPost=(\d+)\]"

something like

Regex reg = new Regex(@"\[quote IdPost=(\d+)\]");
foreach (Match match in reg.Matches(text))
{
   ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

Note that since MatchCollection only implements IEnumerable, match will be an object unless you add .OfType<Match>()
@Aravol good catch, guess I cant just be lazy and use var LOL
I think using RegEx here is overpower.
@aloisdg we use whatever is easy and suits the job to do the tasks isn't it ~~
0
var originalstring = "[quote IdPost=8] Some quoting text [/quote]";

//"[quote IdPost=" and "8] Some quoting text [/quote]"
var splits = originalstring.Split('=');
if(splits.Count() == 2)
{
    //"8" and "] Some quoting text [/quote]"
    var splits2 = splits[1].Split(']');
    int id;
    if(int.TryParse(splits2[0], out id))
    {
        return id;
    }
}

Comments

0

I do not know exactly what is your string, but here is a regex-free solution with Substring :

using System;

public class Program
{
    public static void Main()
    {
        string source = "[quote IdPost=8] Some quoting text [/quote]";

        Console.WriteLine(ExtractNum(source, "=", "]"));
        Console.WriteLine(ExtractNum2(source, "[quote IdPost="));
    }

    public static string ExtractNum(string source, string start, string end)
    {
        int index = source.IndexOf(start) + start.Length;
        return source.Substring(index, source.IndexOf(end) - index);
    }

    // just another solution for fun
    public static string ExtractNum2(string source, string junk)
    {
        source = source.Substring(junk.Length, source.Length - junk.Length); // erase start
        return source.Remove(source.IndexOf(']')); // erase end
    }
}

Demo on DotNetFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.