C0DEPirate
C0DEPirate

Reputation: 125

Merge two conditions in regex

I have a free text field which can contain five words

Allowed pattern for each word is [\w+=,.@-]+

I want to add character length from 1 to 64 characters

for this I created 2 regex and using 'AND' condition but I want to create only one regex How can I do it

a) "[\\w+=,.@-]\\s{0,1}){1,5}"
b) "\\b\\w{1,64}\\b"

Input String

Acceptable -

Test1

Test2

Test3

Test4

Test5

Acceptable - Test1 Test2 Test3 Test4 Test5

Unacceptable - Test1 Test2 Test3 Test4 Test55555555555555555555555555555555555555555555555555555555555555555

I tried this one - (^([\w\.\+\@\,]{1,64}){1}$)|(^([\w\.\+\@\,]{1,64}\s+){1,5}\s{0,1}$)

But the above required an space at the end of last word, if anyone can help with the above one so that it does not require space at end then that will fix my problem

Upvotes: 2

Views: 251

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

If the text field can contain 5 words, and the maximum number of characters in total is 1 to 64, you can use a positive lookahead anchored to the start of the string.

Then you can match 1+ word characters and repeat 1-4 times matching a space and 1+ word character to prevent having to end the string with a space.

^(?=[\w+=,.@ -]{1,64}$)(?:\w+(?: \w+){0,4})$

Explanation

  • ^ Start of string
  • (?= Positive lookahead, assert what is directly to the right is
    • [\w+=,.@ -]{1,64}$ Match any of the listed 1-64 times an assert end of string
  • ) Close lookahead
  • (?: Non capture group
    • \w+ Match 1+ word chars
    • (?: \w+){0,4} Repeat 0-4 times matching a space and 1+ word chars
  • ) close non capture group
  • $ Assert end of string

Regex demo

In Java with double escaped backslashes:

String regex = "^(?=[\\w+=,.@ -]{1,64}$)(?:\\w+(?: \\w+){0,4})$";

Upvotes: 1

Quinn
Quinn

Reputation: 4504

Please have a try of the following pattern:

^(?:\\b[\\w+=,.@-]{1,64}\\b\\s{0,1}){1,5}$

Regex101 - Live Demo

Upvotes: 1

Related Questions