Reputation: 1457
I have this scenario:
Ex1:
Valid:
12345678|abcdefghij|aaaaaaaa
Invalid:
12345678|abcdefghijk|aaaaaaaaa
Which means that between pipes the maximum length is 8. How can I make in the regex?
I put this
^(?:[^|]+{0,7}(?:\|[^|]+)?$
but it´s not working
Upvotes: 0
Views: 1155
Reputation: 627380
When you want to match delimited data, you should refrain from using plain unrestricted .
. You need to match parts between |
, so you should consider [^|]
negated character class construct that matches any char but |
.
Since you need to limit the number of the pattern occurrences of the negated character class, restrict it with a limiting quantifier {1,8}
that matches 1 to 8 consecutive occurrences of the quantified subpattern.
Use
^[^|]{1,8}(?:\|[^|]{1,8})*$
See the regex demo.
Details
^
- start of a string[^|]{1,8}
- any 1 to 8 chars other than |
(?:\|[^|]{1,8})*
- 0 or more consecutive sequences of:
\|
- a literal pipe symbol[^|]{1,8}
- any 1 to 8 chars other than |
$
- end of string.Then, the [^|]
can be restricted further as per requirements. If you only need to validate a string that has ASCII letters, digits, (
, )
, +
, ,
, .
, /
, :
, ?
, whitespace and -
, you need to use
^[A-Za-z0-9()+,.\/:?\s-]{1,8}(?:\|[A-Za-z0-9()+,.\/:?\s-]{1,8})*$
See another regex demo.
Upvotes: 1
Reputation: 522626
Try the following pattern:
^.{1,8}(?:\|.{1,8})*$
The basic idea is to match between one and eight characters, followed by |
and another 1 to 8 characters, that term repeated zero or more times. Explore the demo with any data you want to see how it works.
Sample data:
123
12345678
abcdefghi (no match)
12345678|abcdefgh|aaaaaaaa
12345678|abcdefghijk|aaaaaaaaa (no match)
Demo here:
Upvotes: 3