我正在创建自己的论坛。我引用邮件时遇到问题。我知道如何在文本框中添加引用消息,但我无法弄清楚如何在发布后从字符串中提取值。在文本框中,我有这样的事情:
[quote IdPost=8] Some quoting text [/quote]
[quote IdPost=15] Second quoting text [/quote]
你能说出提取所有" IdPost"的最简单方法是什么?发布表格后来自字符串的数字?
答案 0 :(得分:5)
使用正则表达式
@"\[quote IdPost=(\d+)\]"
类似
Regex reg = new Regex(@"\[quote IdPost=(\d+)\]");
foreach (Match match in reg.Matches(text))
{
...
}
答案 1 :(得分:0)
我不确切知道你的字符串是什么,但这是一个使用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
}
}
答案 2 :(得分: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;
}
}