Regular expression [Any number]

后端 未结 4 499
一个人的身影
一个人的身影 2021-02-02 07:09

I need to test for \"[any number]\" in a string in javascript. how would i match it?

Oh, \"[\" and \"]\" also need to be matched.

so string like \"[1]\" or \"[1

相关标签:
4条回答
  • 2021-02-02 07:24

    UPDATE: for your updated question

    variable.match(/\[[0-9]+\]/);
    

    Try this:

    variable.match(/[0-9]+/);    // for unsigned integers
    variable.match(/[-0-9]+/);   // for signed integers
    variable.match(/[-.0-9]+/);  // for signed float numbers
    

    Hope this helps!

    0 讨论(0)
  • 2021-02-02 07:24
    var mask = /^\d+$/;
    if ( myString.exec(mask) ){
       /* That's a number */
    }
    
    0 讨论(0)
  • 2021-02-02 07:28
    if("123".search(/^\d+$/) >= 0){
       // its a number
    }
    
    0 讨论(0)
  • 2021-02-02 07:32

    You can use the following function to find the biggest [number] in any string.

    It returns the value of the biggest [number] as an Integer.

    var biggestNumber = function(str) {
        var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
    
        while ((match = pattern.exec(str)) !== null) {
            if (match.index === pattern.lastIndex) {
                pattern.lastIndex++;
            }
            match[1] = parseInt(match[1]);
            if(biggest < match[1]) {
                biggest = match[1];
            }
        }
        return biggest;
    }
    

    DEMO

    The following demo calculates the biggest number in your textarea every time you click the button.

    It allows you to play around with the textarea and re-test the function with a different text.

    var biggestNumber = function(str) {
        var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
    
        while ((match = pattern.exec(str)) !== null) {
            if (match.index === pattern.lastIndex) {
                pattern.lastIndex++;
            }
            match[1] = parseInt(match[1]);
            if(biggest < match[1]) {
                biggest = match[1];
            }
        }
        return biggest;
    }
    
    document.getElementById("myButton").addEventListener("click", function() {
        alert(biggestNumber(document.getElementById("myTextArea").value));
    });
    <div>
        <textarea rows="6" cols="50" id="myTextArea">
    this is a test [1] also this [2] is a test
    and again [18] this is a test. 
    items[14].items[29].firstname too is a test!
    items[4].firstname too is a test!
        </textarea>
    </div>
    
    <div>
       <button id="myButton">Try me</button>
    </div>

    See also this Fiddle!

    0 讨论(0)
提交回复
热议问题