如何使用RegEx选择最长的比赛? [英] How do I use RegEx to pick longest match?

查看:42
本文介绍了如何使用RegEx选择最长的比赛?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试寻找此问题的答案,但找不到任何东西,我希望对此有一个简单的解决方案.我在C#中使用以下代码,

I tried looking for an answer to this question but just couldn't finding anything and I hope that there's an easy solution for this. I have and using the following code in C#,

String pattern = ("(hello|hello world)");
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
var matches = regex.Matches("hello world");

问题是,matches方法是否有办法首先返回最长的模式?在这种情况下,我想以"hello world"作为我的比赛,而不是"hello".这只是一个例子,但我的模式列表中包含相当数量的单词.

Question is, is there a way for the matches method to return the longest pattern first? In this case, I want to get "hello world" as my match as opposed to just "hello". This is just an example but my pattern list consist of decent amount of words in it.

推荐答案

如果您已经事先知道单词的长度,则将最长的单词放在第一位.例如:

If you already know the lengths of the words beforehand, then put the longest first. For example:

String pattern = ("(hello world|hello)");

最长的将首先匹配.如果您事先不知道长度,那是不可能的.

The longest will be matched first. If you don't know the lengths beforehand, this isn't possible.

另一种方法是使用语言的内置函数将所有匹配项存储在数组/哈希/列表中,并手动选择最长的匹配项.

An alternative approach would be to store all the matches in an array/hash/list and pick the longest one manually, using the language's built-in functions.

这篇关于如何使用RegEx选择最长的比赛?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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