简体   繁体   中英

regex to separate numbers from comma delimited list

I need a pure regex (no language) to separate the numbers of this input array:

L1,3,5,0,5,80,40,31,0,0,0,0,512,412,213,900

Issues:

  1. The first field ( L1 ) is fixed. The array will always start with L1 .
  2. The other fields will always be 0 or positive numbers.
  3. But I need to acquire each data separately, so it would be:
    A regex for second data (number 3 in the example)
    A regex for third data (number 5 in the example)
    ....
    A regex for sixteenth data (number 900 in the example)

I tried this regex [^;,]* but it wasn't able to get each data separately.

Can anyone help me on this issue?

With 'pure regex' to get each field, you have to use separate capture groups:

^L(\d),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)$

Demo

(Note: In Python, Perl, Ruby, Java, etc you can have a global find and capture like /(\d+)/g but that is the language gathering up the matches into a list...)


If you want just one specific field, you can use numbered repetition.

^L(\d)(,(\d+)){N}

Capture group 3 would always be field N-1 so to capture 213, the 15th field, in your example:

^L(\d)(,(\d+)){14}  

Demo2

Trying to refine dawg's approach such that less capturing groups are used:

The fourth field can be matched by

^L1(?:,(\d+)){3}

Online Test

The fifth field can be matched by

^L1(?:,(\d+)){4}

etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM