Home > database >  Regex adjustment help needed
Regex adjustment help needed

Time:07-13

Currently this regex prevents X.X which is good, it allows X.(space), also good, but it prevents X.(nothing).

If an address may be entered like “My St.”, it doesn't work. Can somebody adjust the regex to allow for a dot followed by nothing?

var test1 = "X.X"; // expected: false, result: false
var test2 = "X. "; // expected: true, result: true
var test3 = "My St."; // expected: true, result: false
var test4 = "My St. "; // expected: true, result: true

var pattern = /^$|^(?:[a-zA-Z\u0080-\uFFFF0-9\s\-#',]|.(?=\s)){0,40}$/;

console.log(pattern.test(test4));

CodePudding user response:

You can omit the ^$ part as the quantifier for the whole non capture group is optional due to the zero in {0,40}

If you want to match a dot at the end of the string, you first have to escape it to match it literally, and then you can assert the start of the string or a whitspace char.

You can write the pattern as:

^(?:[a-zA-Z\u0080-\uFFFF0-9\s#',-]|\.(?=\s|$)){0,40}$

var test1 = "X.X"; // expected: false, result: false
var test2 = "X. "; // expected: true, result: true
var test3 = "My St."; // expected: true, result: false
var test4 = "My St. "; // expected: true, result: true

var pattern = /^(?:[a-zA-Z\u0080-\uFFFF0-9\s#',-]|\.(?=\s|$)){0,40}$/;


console.log(pattern.test(test1));
console.log(pattern.test(test2));
console.log(pattern.test(test3));
console.log(pattern.test(test4));

CodePudding user response:

End your regex with a dot then an optional space \. ?$:

^(?:[a-zA-Z\u0080-\uFFFF0-9\s#-',]){0,40}\. ?$

var test1 = "X.X"; // expected: false, result: false
var test2 = "X. "; // expected: true, result: true
var test3 = "My St."; // expected: true, result: false
var test4 = "My St. "; // expected: true, result: true

var pattern = /^(?:[a-zA-Z\u0080-\uFFFF0-9\s#-',]){0,40}\. ?$/;

console.log(pattern.test(test1));
console.log(pattern.test(test2));
console.log(pattern.test(test3));
console.log(pattern.test(test4));

Also notice minor tweak to character class to remove unnecessary escape of dash by moving it the the end.

  • Related