繁体   English   中英

如何使用正则表达式从下面提取特定的字符串? 最好的方法

[英]how to extract specific string from following using regex? the best way

我有以下类型的字符串

/asdfd-dfsdf-sadfdfsdf-safdsfok-785452145x/dshfkjsd-sdfsd-sdfsdfsn-sfsdfe-jsdfdss/9?sdf=sdfsdf32d-0sdf8d-49sfe-asdf7-4fsfs32dd73880

我只想提取其中的785452145x

最好的方法是什么? 我使用C#2.0

// setup the input data
string inputString = "/asdfd...";

// pull out string from beginning to second slash
// firstPart = "/asdfd...fok-785452145x/"
string firstPart = inputString.Substring(0, inputString.IndexOf("/", 1));

// grab last data element after the last hyphen
// lastElement = "785452145x";
string lastElement = firstPart.Substring(firstPart.LastIndexOf("-") + 1);

// do something with lastElement...

如果您要匹配字符串中的该字符家族,则此正则表达式会将其放在第一个匹配组中。

/[a-z]+-[a-z]+-[a-z]+-[a-z]+-([0-9a-z]+).*

如果您尝试匹配该确切的字符串,则不需要正则表达式。

由于您需要该特定字符串,因此不需要正则表达式。 如果您只是想知道大字符串是否包含要查找的字符串,请尝试

inputString.Contains("785452145x");

这会给您一个布尔值,指示是否找到了字符串。

您要求使用正则表达式...

string answer = Regex.Match(input, @"^/.+-(.+)/.+").Groups[1].Value;

暂无
暂无

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

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