如何使用正则表达式C#在指定的单词后获取单词 [英] How to get word after specified word using regex C#

查看:70
本文介绍了如何使用正则表达式C#在指定的单词后获取单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前列腺特异性抗原1.2 NA NA。 。 。 。 。 。 。年龄高达49 50 - 59 60 - 69超过



我想匹配前列腺特异性抗原这个词,需要得到以下的话





预期成果:

1.2



可能性

< 1.2或> 1.2或< = 1.2,> = 1.2



任何特殊字符或任何特殊字符都将出现在1.2之前我需要选择那个词



我尝试过:



string Pattern =前列腺特异性Antigen \ * *(\d +(\.\ * *)?| \。\ d +);

匹配匹配= Regex.Match (RawContent,Pattern,RegexOptions.IgnoreCase);



if(matches.Success)

{

MessageBox .Show(matches.Groups [1] .Value.ToString());

MessageBox.Show(matches.Value.ToString());

}

Prostate Specific Antigen 1.2 NA NA . . . . . . . Age yrs up to 49 50 - 59 60 - 69 over

I want to match "Prostate Specific Antigen" this word and need to get following word


Expected Result:
1.2

Possibilities
<1.2 or >1.2 or <=1.2, >=1.2

Any special characters or any no of special characters will come before 1.2 but I need to select that word

What I have tried:

string Pattern = Prostate Specific Antigen\s*(\d+(\.\d*)?|\.\d+);
Match matches = Regex.Match(RawContent, Pattern, RegexOptions.IgnoreCase);

if (matches.Success)
{
MessageBox.Show(matches.Groups[1].Value.ToString());
MessageBox.Show(matches.Value.ToString());
}

推荐答案

我更喜欢非正则表达式方法:



I prefer a non-regex approach:

string text = "Prostate Specific Antigen 1.2 NA NA . . . . . . . Age yrs up to 49 50 - 59 60 - 69 over";
string searchTerm = "Prostate Specific Antigen";
string value = string.Empty;
int pos = text.IndexOf(searchTerm);
if (pos >= 0)
{
    string temp = text.Substring(pos + searchTerm.Length).Trim();
    string[] parts = temp.Split(' ');
    value = parts[0];
}





我用显示的字符串测试了代码,文本前置于字符串,只有字符串中的搜索词,最后是一个空字符串。



I tested the code with the string shown, with text prepended to the string, with nothing but the search term in the string, and finally, an empty string.


你可以使用'look behind'分组,但是不支持它(在.NET中你是拥有它)

正则表达式语言 - 快速参考 [ ^ ]



You can use 'look behind' grouping for that, but it is not supported everywhere (in .NET you have it)
Regular Expression Language - Quick Reference[^]

(?<=\bProstate Specific Antigen\s)(\w+)


尝试RegEx:前列腺特异性抗原+(+ [^] +)\ s

Try RegEx: "Prostate Specific Antigen\s+([^ ]+)\s"
string Pattern = "Prostate\\ Specific\\ Antigen\\s{1,}([^\\ ]+)\\s";





这是Reg的一个Ex文档:

perlre - perldoc.perl.org [ ^ ]

以下是帮助构建RegEx并调试它们的工具的链接:

.NET正则表达式测试程序 - 正则表达式风暴 [ ^ ]

Expresso Regular表达工具 [ ^ ]

这个显示RegEx是一个很好的图表,它非常有助于理解RegEx的作用:

Debuggex :在线视觉正则表达式测试。 JavaScript,Python和PCRE。 [ ^ ]



Here is a to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]


这篇关于如何使用正则表达式C#在指定的单词后获取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆