I am facing a weird issue with Regex. My expression working fine in https://regexr.com/3cr6f But when i use the same expression in my code then it start failing.
This is my Expression:
^([a-zA-Z] \\) (Documents){1}\\{1}((CT([A-Za-z]){0,2})|(FE)|(FF))$
I want to test this expression on my typescript string:
var case1='User\Folders\MyDocuments\CTTV';
var case2='User\Folders\MyDocuments\FE';
var case3='User\Folders\MyDocuments\FF';
But it always return me null.
var regex = new RegExp(/^([a-zA-Z] \\) (Documents){1}\\{1}((CT([A-Za-z]){0,2})|(FE)|(FF))$/);
regex.test(case1); //false
Might be someone else also faced such issue in Javascript typescript.
CodePudding user response:
As pointed out by one of the comments, the test strings are MyDocuments
but your regex has Documents
. If you adjust your regex to this:
^([a-zA-Z] \\) (MyDocuments){1}\\{1}((CT([A-Za-z]){0,2})|(FE)|(FF))$
It works fine
https://regex101.com/r/xoGaue/1
CodePudding user response:
So the reason why it does not work at the moment is that you are trying to match the string myDocuments to Documents.
To fix your regex I would add a partial match for regex by adding .*?
this will match any possible characters.
^([a-zA-Z] \\) (.*?Documents.*?){1}\\{1}((CT([A-Za-z]){0,2})|(FE)|(FF))
but I would change your regex all together:
if you do not care about the document folder then I would suggest:
^(. )\\ ((CT([A-Za-z]){0,2})|(FE)|(FF))$
else you can use:
^(. )\\ (.*?Documents.*?){1}\\((CT([A-Za-z]){0,2})|(FE)|(FF))$
see here:
https://regex101.com/r/qd4Fjs/1
CodePudding user response:
- add "My" to "Documents"
- use String.raw`` to escape backslash
Check it out": https://playcode.io/918676/
let
case1=String.raw`User\Folders\MyDocuments\CTTV`,
case2=String.raw`User\Folders\MyDocuments\FE`,
case3=String.raw`User\Folders\MyDocuments\FF`,
case4=String.raw`User\Folders\MyDocuments\False`
let regex = new RegExp(/^([a-zA-Z] \\) (MyDocuments){1}\\{1}((CT([A-Za-z]){0,2})|(FE)|(FF))$/);
console.log(
regex.test(case1),
regex.test(case2),
regex.test(case3),
regex.test(case4)
)