简体   繁体   English

RegEx测试方法应为true时返回false

[英]RegEx test method returns false when it should be true

I've tested the three of the regex's on http://www.regexpal.com/ and they are what I need, but when doing a regex test 2 of them return false (BTC and CAD) and only the Bitcoin address seems to work (you may test with this wallet below). 我已经在http://www.regexpal.com/上测试了三个正则表达式,它们是我所需要的,但是在进行正则表达式测试时,其中两个返回假(BTC和CAD),并且似乎只有比特币地址工作(您可以在下面使用此钱包进行测试)。

13dHNxtbckAFM4PzdBqWgymFJmcv3Yzi32 13dHNxtbckAFM4PzdBqWgymFJmcv3Yzi32

https://jsfiddle.net/ps2fj1ff/1 (all the relevant code is in the html section) https://jsfiddle.net/ps2fj1ff/1 (所有相关代码在html部分中)

    var regWallet = new RegExp("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$");
    var regBTC = new RegExp("^\d*\.\d*$");
    var regCAD = new RegExp("^\d+(\.(\d{2}))?$");

    $('#button1').on('click', function() {

        var btcCheck = $('#amount_btc').val();  

        if (regBTC.test(btcCheck)) {

        } else {
            alert("Invalid BTC value!");
        }

        var cadCheck = $('#amount_cad').val();  

        if (regCAD.test(cadCheck)) {

        } else {
            alert("Invalid CAD value!");
        }

        var walletCheck = $('#wallet').val();
        if (regWallet.test(walletCheck)) {

        } else {
            alert("Invalid Bitcoin address, please make sure you've entered a valid address!");
        }
    }); 

The reason is that in var regBTC = new RegExp("^\\d*\\.\\d*$"); 原因是在var regBTC = new RegExp("^\\d*\\.\\d*$"); the \\ is used to escape the character so if you console.log(regBTC) you will see it as ^d*.d*$ . \\用于转义字符,因此如果您console.log(regBTC)您将看到它为^d*.d*$

To prevent this you will have to double escape it: var regBTC = new RegExp("^\\\\d*\\\\.\\\\d*$"); 为了防止这种情况,您将不得不对其进行两次转义: var regBTC = new RegExp("^\\\\d*\\\\.\\\\d*$");

Or better yet use / instead: var regBTC = /^\\d*\\.\\d*$/; 最好还是使用/代替: var regBTC = /^\\d*\\.\\d*$/;

The same goes for the other regex too. 其他正则表达式也是如此。

(I initially thought single quote would work too, but apparently not in javascript) (我起初以为单引号也可以,但显然不能在javascript中使用)

Use this instead: 使用此代替:

var regBTC = /^\d*\.\d*$/;
var regCAD = /^\d+(\.(\d{2}))$/;

It's cleaner and more readable as most editors will give you regexp syntax highlighting in this format. 它更干净,更易读,因为大多数编辑器都会以这种格式为您提供正则表达式语法高亮显示。

There really isn't any good reason to use new RegExp which forces you to write the expression as a string, which forces you to use confusing escapes, when there is a proper regular expression syntax built into JavaScript. 确实没有充分的理由使用new RegExp ,它会在JavaScript中内置适当的正则表达式语法时强制您将表达式编写为字符串,从而迫使您使用令人困惑的转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM