简体   繁体   English

字母v的正则表达式前加下划线…,后跟任意长度的数字

[英]Regex for letter v preceded by underscore…and followed by any length number

I have a string like below 我有一个像下面的字符串

string a= "idh_abcdef_normal_verymuch_ext_v1_20131101000000";

How do I find the index of "_v1" (small letter v followed by a number ( of any length ). 如何找到“ _v1”(小写字母v后跟数字( 任意长度 ))的索引。

Below code is not working :( 下面的代码不起作用:(

Console.WriteLine(System.Text.RegularExpressions.Regex.Match(a,"^[v][0-9]$").Index);

could someone help me please. 有人可以帮我吗。

If you are sure that the string contains the given substring: 如果您确定该字符串包含给定的子字符串:

int index = Regex.Match(s, "_v\\d").Index;

otherwise 除此以外

Match match = Regex.Match(s, "_v\\d");
if (match.Success)
    index = match.Index;

The problem with your regex: 正则表达式的问题:

^[v][0-9]$

Is that you are using a pattern to start with v and finish with a number. 是您正在使用以v开头并以数字结尾的模式。 So, only strings like v0 , v2 ... v9 are valid. 因此,只有像v0v2 ... v9这样的字符串才有效。 Btw, you don't need to use [v] since it's exactly the same as v . 顺便说一句,您不需要使用[v]因为它与v完全相同。

You can use a regex look ahead like this: 您可以像这样使用正则表达式前瞻:

_v(?=\d)

Working demo 工作演示

Or a simple regex 或简单的正则表达式

_v\d

Working demo 工作演示

Use: 采用:

_v\d+

As the regex you need. 作为正则表达式,您需要。

Why not a simple search: 为什么不简单搜索:

string searchString = "_v1_";
int index = a.IndexOf(searchString);
string sNumber = a.Substring(index + searchString.Length);
long lNumber = long.Parse(sNumber);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM