neel.1708
neel.1708

Reputation: 315

Need regular expression for pattern this

I need a regular expression for below pattern

  1. It can start with / or number
  2. It can only contain numbers, no text
  3. Numbers can have space in between them.
  4. It can contain /*, at least 1 number and space or numbers and /*

Valid Strings:

 3232////33 43/323//
 3232////3343/323//
 /3232////343/323//

Invalid Strings:

/sas/3232/////dsds/    
/ /34343///// /////
///////////

My Problem is, it can have space between numbers like /3232 323/ but not / /.
How to validate it ?

I have tried so far:

(\\d[\\d ]*/+) , (/*\\d[\\d ]*/+) , (/*)(\\d*)(/*)

Upvotes: 0

Views: 96

Answers (5)

Lpc_dark
Lpc_dark

Reputation: 2940

"(?![A-z])(?=.*[0-9].*)(?!.*/ /.*)[0-9/ ]{2,}(?![A-z])"

this will match what you want but keep in mind it will also match this

/3232///// from /sas/3232/////dsds/ 

this is because part of the invalid string is correct

if you reading line by line then match the ^ $ and if you are reading an entire block of text then search for \r\n around the regex above to match each new line

Upvotes: 0

Bohemian
Bohemian

Reputation: 424983

Try this java regex

/*(\\d[\\d ]*(?<=\\d)/+)+

It meets all your criteria.

Although you didn't specifically state it, I have assumed that a space may not appear as the first or last character for a number (ie spaces must be between numbers)

Upvotes: 0

Loamhoof
Loamhoof

Reputation: 8293

Just use lookarounds for the last criteria.

^(?=.*?\\d)([\\d/]*(?:/ ?(?!/)|\\d ?))+$

The best would have been to use conditional regex, but I think Java doesn't support them.

Explanation:
Basically, numbers or slashes, followed by one number and a space, or one slash and a space which is not followed by another slash. Repeat that. The space is made optional because I assume there's none at the end of your string.

Upvotes: 0

anubhava
anubhava

Reputation: 784998

This regex should work for you:

^/*(?:\\d(?: \\d)*/*)+$

Live Demo: http://www.rubular.com/r/pUOYFwV8SQ

Upvotes: 1

Petr Behensk&#253;
Petr Behensk&#253;

Reputation: 620

My solution is not so simple but it works

^(((\d[\d ]*\d)|\d)|/)*((\d[\d ]*\d)|\d)(((\d[\d ]*\d)|\d)|/)*$

Upvotes: 0

Related Questions