-4

用于验证 ( ::number::sentence::) 此类值的正则表达式如何?

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

2 回答 2

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::");
于 2013-08-05T09:03:23.587 回答
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

但是在“捕获”“任何字符”之前进行检查:(?!::)任何字符和下一个字符都不是::(它被称为零宽度负前瞻

于 2013-08-05T09:04:24.803 回答