[英]Regex first digits occurrence
My task is extract the first digits in the following string: 我的任务是提取以下字符串中的前几个数字:
GLB=VSCA|34|speed|1|
My pattern is the following: 我的模式如下:
(?x:VSCA(\|){1}(\d.))
Basically I need to extract "34", the first digits occurrence after the "VSCA". 基本上,我需要提取“ 34”,即“ VSCA”之后的第一个数字。 With my pattern I obtain a group but would be possibile to get only the number?
按照我的模式,我可以建立一个小组,但是只能得到数字吗? this is my c# snippet:
这是我的C#代码段:
string regex = @"(?x:VSCA(\|){1}(\d.))";
Regex rx = new Regex(regex);
string s = "GLB=VSCA|34|speed|1|";
if (rx.Match(s).Success)
{
var test = rx.Match(s).Groups[1].ToString();
}
You could match 34
(the first digits after VSCA
) using a positive lookbehind (?<=VSCA\\D*)
to assert that what is on the left side is VSCA
followed by zero or times not a digit \\D*
and then match one or more digits \\d+
: 您可以使用正向后
VSCA
(?<=VSCA\\D*)
来匹配34
( VSCA
之后的第一位数字(?<=VSCA\\D*)
以断言左侧的内容是VSCA
然后是零或不是数字\\D*
,然后匹配一个或更多数字\\d+
:
If you need the pipe to be after VSCA
the you could include that in the lookbehind: 如果您需要将管道放在
VSCA
之后,则可以将其包括在VSCA
:
This regex pattern: (?<=VSCA\\|)\\d+?(?=\\|)
will match only the number. 此正则表达式模式:
(?<=VSCA\\|)\\d+?(?=\\|)
仅匹配数字。 (If your number can be negative / have decimal places you may want to use (?<=VSCA\\|).+?(?=\\|)
instead) (如果您的数字可以为负数/小数位,则可以使用
(?<=VSCA\\|).+?(?=\\|)
代替)
You don't need Regex for this, you can simply split on the '|'
您不需要正则表达式,只需在
'|'
上分割即可 character: 字符:
string s = "GLB=VSCA|34|speed|1|";
string[] parts = s.Split('|');
if(parts.Length >= 2)
{
Console.WriteLine(parts[1]); //prints 34
}
The benefit here is that you can access all parts of the original string based on the index: 这样做的好处是您可以根据索引访问原始字符串的所有部分:
[0] - "GLB=VSCA"
[1] - "34"
[2] - "speed"
[3] - "1"
While the other answers work really well, if you really must use a regular expression, or are interested in knowing how to get to that straight away you can use a named group for the number. 尽管其他答案确实非常有效,但是如果您确实必须使用正则表达式,或者对知道如何立即使用正则表达式感兴趣,则可以为该数字使用命名组。 Consider the following code:
考虑以下代码:
string regex = @"(?x:VSCA(\|){1}(?<number>\d.?))";
Regex rx = new Regex(regex);
string s = "GLB:VSCA|34|speed|1|";
var match = rx.Match(s);
if(match.Success) Console.WriteLine(match.Groups["number"]);
How about (?<=VSCA\\|)[0-9]+
? (?<=VSCA\\|)[0-9]+
怎么样?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.