我有一个字符串,如:"abc xyz: ID# 1000123, this is test, test 1, test 1234, "
我需要编写一个正则表达式来提取 ID 1000123。
我尝试过一些类似的东西:
Regex betweenOfRegexCompiled = new Regex("ID# (.*), ", RegexOptions.Compiled);
但它给出“1000123,这是测试,测试 1,测试 1234”。
那么,如何指定 的第一次出现", "?
而不是.*使用\d+:
"ID# (\d+)"
.*匹配任意数量的字符。\d+匹配一个或多个数字(如果要排除非西方数字,请使用[0-9]代替\d)。
这是(更有效的)非正则表达式方法:
string text = "abc xyz: ID# 1000123, this is test, test 1, test 1234, ";
string id = null;
int idIndex = text.IndexOf("ID# ");
if(idIndex != -1)
{
idIndex += "ID# ".Length;
int commaIndex = text.IndexOf(',', idIndex);
if(commaIndex != -1)
id = text.Substring(idIndex, commaIndex - idIndex);
else
id = text.Substring(idIndex);
}
试试这个 reg,它应该完全是数字
(?<=ID\#\s)\d+(?=\,)
如果在ID#之后和之前找到数字,
获取数字(即所有字符,但不包括第一个逗号)...
"ID# ([^,]*),"
如果你想让它的数字明确,那么......
"ID# ([0-9]*),"
对于非正则表达式版本...
string text = "abc xyz: ID# 1000123, this is test, test 1, test 1234, ";
string num = text.Split(new Char[] {','})[0].Split(new Char[] {' '})[3];