What regular expression can I use to find the Nᵗʰ entry in a comma-separated list?

前端 未结 3 2113
无人及你
无人及你 2021-01-02 12:04

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

For example, say this list looks like this:



        
相关标签:
3条回答
  • 2021-01-02 12:23

    You could use something like:

    ([^,]*,){$m}([^,]*),
    

    As a starting point. (Replace $m with the value of (n-1).) The content would be in capture group 2. This doesn't handle things like lists of size n, but that's just a matter of making the appropriate modifications for your situation.

    0 讨论(0)
  • 2021-01-02 12:33
    @list = split /,/ => $string;
    $it = $list[6];
    

    or just

    $it = (split /,/ => $string)[6];
    

    Beats writing a pattern with a {6} in it every time.

    0 讨论(0)
  • 2021-01-02 12:46

    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}([^,]*)/

    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.

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

    0 讨论(0)
提交回复
热议问题