用于解析:: number :: sentence ::的正则表达式

时间:2013-08-05 09:00:31

标签: c# .net regex

验证的正则表达式(::number::sentence::)如何看待这样的值?

::1::some text::
::2::some text's::
::234::some's text's::

2 个答案:

答案 0 :(得分:5)

你可以使用String.Split并完全避免正则表达式,如果你的字符串就像这样简单。

var data = "::234::some's text's::".Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(data[0]); // 234
Console.WriteLine(data[1]); // some's text's

如果您需要使用它进行验证,您仍然可以使用与上述相同的逻辑,例如

public bool Validate(string str)
{
    var data = str.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
    double n;
    return data.Length == 2 && Double.TryParse(data[0], out n) && !String.IsNullOrWhiteSpace(data[1]);
}
...
bool valid = Validate("::234::some's text's::");

答案 1 :(得分:1)

类似的东西:

^::([0-9]+)::((?:(?!::).)*)::$

示例代码:

Match match = Regex.Match("::1::some text::", "::([0-9]+)::((?:(?!::).)*)::");
var groups = match.Groups;
string num = groups[1].ToString();
string text = groups[2].ToString();

说明:

^ Begin of the string
:: 2x ':'
([0-9]+) Match group 1, the 0-9 digits, one or more
:: 2x ':'
((?:(?!::).)*) Match group 2, any one character that isn't ::, zero or more
:: 2x ':'
$ End of the string

((?:(?!::).)*)需要更多解释......让我们剥离它......

( ... ) the first '(' and last ')', match group 2

现在我们有:

(?:(?!::).)*

所以

(?: ... )* group without name (non capturing group) repeated 0 or more times. Its content will be put in match group 2 because it's in defined inside match group 2

由:

组成
(?!::). 

,其中

. is any character

但是在“捕获”“任何角色”之前,请检查:(?!::)任何角色和下一个角色都不是::(它被称为零宽度负向前瞻< / em>的)