2011-02-08 14 views
21

JavaScriptで文字列の "[任意の数]"をテストする必要があります。どのように私はそれに一致するだろうか?正規表現[任意の番号]

ああ、「[」と「]」も一致させる必要があります。

"[1]"や "[12345]"のような文字列は一致します。

非一致: "[23432" または "1]" は、例えばので

:アイテム」に "アイテム[0] .firstname":私は入力を交換する必要が

$('.form .section .parent').find('input.text').each(function(index){ 
     $(this).attr("name", $(this).attr("name").replace("[current]", "['"+index+"']")); 
}); 

が名をフィールド[1] .firstname」 感謝

+0

http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric – mdrg

答えて

42

UPDATE:あなたの更新のための質問

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

これを試してみてください:

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

は、この情報がお役に立てば幸い!

+0

私はこの$(this).attr( "name"、$(this).attr( "name") .replace( "/ \\ [[0-9] + \\] /"、 "['" + index + "']"));それは動作しません。何か間違っているのですか? – ShaneKm

+1

心配しないでください。それは動作します:var name = $(this).attr( "name"); var newname = $(this).attr( "name")。replace(name.match(/ \\ [[0-9] + \\] /)、 "[" + index + "]"); – ShaneKm

+0

@aorcsik Life saver :) –

0
var mask = /^\d+$/; 
if (myString.exec(mask)){ 
    /* That's a number */ 
} 
2
if("123".search(/^\d+$/) >= 0){ 
    // its a number 
} 
0

あなたは、任意の文字列で最大の[number]を検索するには、次の機能を使用することができます。

最大の値[number]を整数として返します。

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は

次のデモでは、あなたのテキストエリアにこのボタンをクリックするたびに最大の数を計算します。

これで、テキストエリアで遊んで、別のテキストで関数を再テストすることができます。

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>

this Fiddle参照してください!