Thursday 18 March 2021

How to limit the character range in regular expression?

Lets say,

let sentence= "Dear user {#val#}{#val#} thanks"

{#val#} is the dynamic value in the above sentence. Here in place of {#val#}, there can be any values but atleast 0 and maximum 5 characters can be there. So I'm substituting the {#val#} as .{0,5} . I dont need to consider spaces except for the {#val#} portion, so my formed regex would be,

let regex =  /^Dear\s*user\s*.{0,5}.{0,5} thanks$/i
let customermsg = "Dear user 1 2 thanks" //Should be valid
let customermsg1 = "Dear user 12345 6789 thanks" //Should be valid
let customermsg2 = "Dear user 123 5 6789 thanks" //Should be valid because space can also be considered as a character and for fist .{0,5} => 123 5 and for second .{0,5} => 6789
let customermsg3 = "Dear user 1 thanks" //Should pass 
let customermsg4 = "Dea r user 1 tha nks" // Should Pass since spaces are not considered in the static portion.

but when I try to test using below,

 regex.test(customermsg)

Its quite opposite. Even I have tried the below,

let splitters=/{\\#val\\#}|((\\s\*))/gi;
sentence = sentence.replace(splitters, (x, y) => y ? y : ".(\\S{0,5})"); 

This returns the regex as,

 /^Dear\s*user\s*.(\S{0,5}).(\S{0,5})\s*thanks$/

But this is also not working as expected. I'm stuck on this. Please help me.



from How to limit the character range in regular expression?

No comments:

Post a Comment