javascript全局捕获中的正则表达式失败

时间:2016-01-09 07:35:44

标签: javascript regex

var r = new RegExp('^[0-9]*$');
function validatePIN (pin) {
  //return true or false
  if(r.test(pin) && pin.length == 4 || pin.length == 6){
    return true;
  }else{
    return false;
  }
}

console.log(validatePin(3627i1));

上面我的正则表达式有什么问题?在这种情况下,我希望true

3 个答案:

答案 0 :(得分:0)

==4264== HEAP SUMMARY: ==4264== in use at exit: 64 bytes in 2 blocks ==4264== total heap usage: 4,913 allocs, 4,911 frees, 364,063 bytes allocated ==4264== ==4264== LEAK SUMMARY: ==4264== definitely lost: 0 bytes in 0 blocks ==4264== indirectly lost: 0 bytes in 0 blocks ==4264== possibly lost: 0 bytes in 0 blocks ==4264== still reachable: 64 bytes in 2 blocks ==4264== suppressed: 0 bytes in 0 blocks ==4264== Rerun with --leak-check=full to see details of leaked memory ==4264== ==4264== For counts of detected and suppressed errors, rerun with: -v ==4264== Use --track-origins=yes to see where uninitialised values come from ==4264== ERROR SUMMARY: 13582 errors from 542 contexts (suppressed: 0 from 0) your json structure is invalid change it to below structure first { "Birthday": [{ "Name": "Gyanendra Bajpai(11198)", "Date": "08 Jan 2016", "EventCategory": "Birthday", "EmployeeID": "145" }] } //parse json JSONObject result = null; result="";//pass ur response jsonobject to result param here. JSONArray jaResBirthdayList = result.getJSONArray("Birthday"); for (int w = 0; w < jaResBirthdayList.length(); w++) { JSONObject jsonObject =jaResBirthdayList.getJSONObject(w); String NameStr= jsonObject.getString("Name"); String DateStr = jsonObject.getString("Date"); String EventCategoryStr =jsonObject.getString("EventCategory"); String EmployeeIDStr =jsonObject.getString("EmployeeID"); } 不同,validatePinvalidatePIN不同。

因此,请确保调用正确的函数并将其传递给正确的参数:

3627i1

答案 1 :(得分:0)

代码中的语法错误

'3627i1'

答案 2 :(得分:0)

没有什么不对,但这些条件无法正确评估:

struct S

由于S<Widget*> SWP; 的运算符优先级高于r.test(pin) && pin.length == 4 || pin.length == 6 ,因此它有效地表示(r.test(pin) && pin.length == 4) || pin.length == 6

您需要将条件括在括号中:

&&

顺便说一下,你甚至不需要检查长度,因为你可以在正则表达式中做到这一点:

||

现在这个正则表达式将匹配4位数字或6位数字。