What regular expression can I use to find the Nᵗʰ entry in a comma-separated list?
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.
Jared
I work for Amazon Web Services. Opinions expressed on social media are my own.
Updated on July 21, 2022Comments
-
Jared almost 2 years
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:
abc,def,4322,[email protected],3321,alpha-beta,43
...and I wanted to find the value of the 7th entry (
alpha-beta
). -
gymbrall about 12 yearsI believe this also works in Java, though you may need to use the group property and it would be the second element in the group array.