Search code examples
javascriptregexregexp-replace

Issue in regex for a valid format


I am adding a restriction on string using the regex pattern matching but it is not working as i have not much experience in regex. Like there can't be no ( without ) or [ without ].

abc.(%      -->false
abc.)%      -->false
abc.(%]     -->false
abc.)%]     -->false
1abc9.(%[   -->false
abc.)%[     -->false
abc.(%(     -->false
abc.)%)     -->false
19.(%)%     -->true
19.[%]%     -->true
2009% --> true
19.1245 -- true 
10.[5-9]% -- true
/^[^\s\[\]^$.|A-Z]*(?:(?:\[[^\s\[\]\\]+](?!\])|%[^\r\n\?\$\*\.\[\+\(\)\]\.\^%]+%(?=\||$)|\|[^\s\[\]^A-Z\\]+)[^\s\[\]^$.|?*+()A-Z\\]*)*$/

The string is fine if it have start with ( and end with )
19[1-3] is fine
2014.56(core) is fine


Solution

  • I would probably go about this using a whitelist of what is allowed, rather than trying to run around and cover every negative case. That is, use the following regex pattern:

    ^\S+\.(?:(?:\(%\)|\[%\])%?)?$
    

    Demo

    Some JS code:

    var valid = "19.(%)";
    if (/^\S+\.(?:(?:\(%\)|\[%\])%?)?$/.test(valid)) {
        console.log("VALID:   " + valid);
    }
    
    var invalid = "abc.(%";
    if (!/^\S+\.(?:(?:\(%\)|\[%\])%?)?$/.test(invalid)) {
        console.log("INVALID: " + invalid);
    }