简体   繁体   中英

regex to match a recurring pattern

I am trying to write a regex for java that will match the following string:

number,number,number (it could be this simple or it could have a variable number of numbers, but each number has to have a comma after it there will not be any white space though)

here was my attempt:

[[0-9],[0-9]]+

but it seems to match anything with a number in it

You could try something along the lines of ([0-9]+,)*[0-9]+

This will match:

  • Only one number, eg: 7
  • Two numbers, eg: 7,52
  • Three numbers, eg: 7,52,999
  • etc.

This will not match:

  • Things with spaces, eg: 7, 52
  • A list ending with a comma, eg: 7, 52,
  • Many other things out of the scope of this problem.

I think this would work

\d+,(\d+,)+

Note that as you want, that will only capture number followed by a comma

I guess you are starting with a String. Why don't you just use String.split(",") ?

^ means the start of a string and $ means the end. If you don't use those, you could match something in the middle ( b matched "abc").

The + works on the element before it. b is an element, [0-9] is an element, and so are groups (things wrapped in parenthesis).

So, the regex you want matches:

  • The start of the string ^
  • a number [0-9]
  • any amount of comas flowed by numbers (,[0-9])+
  • the end of the string $

or, ^[0-9](,[0-9])+$

Try regex as [\\d,]* string representation as [\\\\d,]* eg below:

   Pattern p4 = Pattern.compile("[\\d,]*");
   Matcher m4 = p4.matcher("12,1212,1212ad,v");
   System.out.println(m4.find()); //prints true
   System.out.println(m4.group());//prints 12,1212,1212

If you want to match minimum one comma (,) and two numbers eg 12,1212 then you may want to use regex as (\\d+,)+\\d+ with string representation as \\\\d+,)+\\\\d+ . This regex matches aa region with a number minimum one digit followed by one comma(,) followed by minimum one digit number.

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