的第一个和最后一次出现删除字符串的一部分,我有一个这样的字符串:获取和性格
继承人如何其设置:
{username:password}data
我怎样才能得到的{用户名:密码}部分,并从完整的字符串中删除它?我需要检查用户名和密码,然后将数据({something:something}之后的所有内容)发送给用户。
最好我想获得的用户名:没有密码的{}这样我就可以通过拆分刚:
的第一个和最后一次出现删除字符串的一部分,我有一个这样的字符串:获取和性格
继承人如何其设置:
{username:password}data
我怎样才能得到的{用户名:密码}部分,并从完整的字符串中删除它?我需要检查用户名和密码,然后将数据({something:something}之后的所有内容)发送给用户。
最好我想获得的用户名:没有密码的{}这样我就可以通过拆分刚:
你可先用substring
和index of
删除不想要的字符。
string input = {username:password}data
input = input.Substring(input.IndexOf("}") +1); //data
这会给你数据部分假设}只出现一次。
哎呀,我的坏。将修改它。感谢您指出。 –
我不认为这是如何工作,无论如何,'input.Substring(input.IndexOf(“}”));'将返回数据'子字符串返回文本开始在您的索引,或两个索引之间,如果你提供开始和结束。 – Andrew
是的,你说得对,我现在修好了。之前是错误的。 –
这里是一个正则表达式的解决方案:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "{something:something}Some data will be here";
string pattern = @"\{(?'username'[^:]+):(?'password'[^\}]+)\}(?'data'.*)";
Match match = Regex.Match(input,pattern);
Console.WriteLine("Username : '{0}', Password : '{1}', Data : '{2}'",
match.Groups["username"].Value, match.Groups["password"].Value, match.Groups["data"].Value);
Console.ReadLine();
}
}
}
public int IndexOfNth(string str, string value, int nth)
{
int offset = str.IndexOf(value);
for (int i = 0; i < nth; i++)
{
if (offset == -1) return -1;
offset = str.IndexOf(value, offset + 1);
}
return offset;
}
这个方法返回你要查找的前值的指数)@弗朗的str
和的nth
位置前)2将返回第3在克里斯@的@一次出现这样@ SK @
此可用于子Strings
也许这将工作:
string x= "{username:password}data";
string username = x.substring(1,IndexoOfNth(x,":",0)-1);
尝试使用正则表达式 – FCin
你尝试过这么远吗?你用Google搜索了什么? – taquion
我在google上找不到任何东西.. – Keriosk