我可以使用什么正则表达式在逗号分隔的列表中找到Nᵗʰ项? [英] What regular expression can I use to find the Nᵗʰ entry in a comma-separated list?

查看:121
本文介绍了我可以使用什么正则表达式在逗号分隔的列表中找到Nᵗʰ项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可用于以逗号分隔的列表中找到第 N th 项的正则表达式。

I need a regular expression that can be used to find the Nth entry in a comma-separated list.

例如,说此列表如下:

abc,def,4322,mail@mailinator.com,3321,alpha-beta,43

...我想找到7 < sup> th 条目( alpha-beta )。

...and I wanted to find the value of the 7th entry (alpha-beta).

推荐答案

我的第一个想法不是使用正则表达式,而是使用将字符串拆分为逗号数组的方法,但是由于您要使用正则表达式。

My first thought would not be to use a regular expression, but to use something that splits the string into an array on the comma, but since you asked for a regex.

大多数正则表达式允许您指定最小或最大匹配,因此类似的操作可能会起作用。

most regexes allow you to specify a minimum or maximum match, so something like this would probably work.

/(?? [[^ \ \,] * \,){6}([^,] *)/

这旨在匹配任意数量的字符不是逗号,然后是正好是(?:[^,] *,){6}六倍的逗号{6} -?:说不捕获-然后匹配并捕获任何不是逗号的字符数([^,] +)。您想使用第一个捕获组。

This is intended to match any number of character that are not a comma followed by a comma six times exactly (?:[^,]*,){6} - the ?: says to not capture - and then to match and capture any number of characters that are not a comma ([^,]+). You want to use the first capture group.

让我知道是否需要更多信息。

Let me know if you need more info.

编辑:我对上面的内容进行了编辑,以不捕获字符串的第一部分。此正则表达式可在C#和Ruby中使用。

I edited the above to not capture the first part of the string. This regex works in C# and Ruby.

这篇关于我可以使用什么正则表达式在逗号分隔的列表中找到Nᵗʰ项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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