Home > Software engineering >  RegEx for String Validation [x_name1_zded|we3e_name2_235|yyy_name3_3435]
RegEx for String Validation [x_name1_zded|we3e_name2_235|yyy_name3_3435]

Time:05-10

I have requirement to check, is getting valid input in the product

Example Product String = "x_name1_zded|we3e_name2_235|yyy_name3_3435"

each protect is delimited with "|".

each productInfo is delimited with "_"

in this example 3 products are there

1-> x_name1_zded

2-> we3e_name2_235

3-> yyy_name3_3435

and each product has 3 details, example product 1 id:x, name: name1, store: zded.

i need RegEx to validate if we have delimited with "|", the minimum 3 section(id,name, store) should be there, user can send N number of product with "|". so RegEx should validate if product is there, than should have 3 section.

Iam trying to do it in Json schema validator, in pattern section

CodePudding user response:

Suppose, each details section can contain a-z letters and 0-9 digits, at least 1 symbol. Detail section will be [a-z0-9] . We have to have at least 3 section divided by _ - there is one section, then at least 2 sequences of "delimiter section" (pseudocode):

section (delimiter section)*(2 or more times)

In regex a single product will be:

[a-z0-9] (_[a-z0-9] ){2,}

Next. It can be N products. If N is any value greater or equals to 1 - then we can use the same schema:

product (delimiter product)*(zero or more times)

So final version of regex is:

[a-z0-9] (_[a-z0-9] ){2,}(\|[a-z0-9] (_[a-z0-9] ){2,})*

\| is escaped delimiter, because | is regex metasymbol. * means "zero or more times".

You can replace [a-z0-9] on any another regexp describes your details section.

For instance, see example.

  • Related