Reputation: 2497
I would like to validate the DNF (Disjunctive normal form) which looks like this A*B+A'*C+C*D*E'
. For this purpose, I use the folloing following pattern:
/[A-Z]'?(\*[A-Z]'?)*(\+[A-Z]'?(\*[A-Z]'?)*)+/g
I have tested this pattern using javascript test() method in this online tool: http://www.pagecolumn.com/tool/regtest.htm and it gives me the result I have expected.
I tried to test the pattern with javascript, using the following code:
<script type="text/javascript">
var dnf="A*3+A*B+CD";
var pattern= /[A-Z]'?(\*[A-Z]'?)*(\+[A-Z]'?(\*[A-Z]'?)*)+/g;
var flag = false;
flag=pattern.test(dnf);
console.log(flag);
</script>
The problem is, I don't understand, why flag (in this code) become "true", which has to be "false" cause the terms A*3 and CD in the dnf="A*3+A*B+CD"
.
I have testet this in the online tester and it says: no matches, what I think is right.
Upvotes: 2
Views: 832
Reputation: 208555
I think you must have entered this into the online tester incorrectly, because I tried the same thing and it is matching "A*B+C"
from the string "A*3+A*B+CD"
:
If you only want to match if the entire string matches your pattern, add start and end of string anchors:
/^[A-Z]'?(\*[A-Z]'?)*(\+[A-Z]'?(\*[A-Z]'?)*)+$/g
Upvotes: 0
Reputation: 55678
You aren't specifying that the match has to begin at the beginning of the string or end at the end of it. So if a substring matches, the pattern test will return true
. In this case, it looks like A*B+C
(a substring of your original string) will match the pattern.
To fix, require that the whole string is matched, using ^
and $
:
var pattern= /^[A-Z]'?(\*[A-Z]'?)*(\+[A-Z]'?(\*[A-Z]'?)*)+$/;
Note that the g
flag no longer makes any sense in this context, as you can only have one match.
Upvotes: 1