2017-06-30 25 views

回答

0

怎麼樣簡單的東西: https://regex101.com/r/g6uBF4/1

^((\(\d{3}\))|(\d{3}-))\d{3}-\d{4} 

只是測試單獨每種情況。括號內的3位數字(\d{3}\)| 3位數字,帶短劃線(\d{3}-)。然後其餘的號碼\d{3}-\d{4}

0

一般而言,如果可以有無限數量的嵌套,則不能使用Javascript正則表達式來確保括號正確平衡圓括號,你需要遞歸/平衡匹配,但你的情況並不複雜。例如,你可以在你的正則表達式的開始添加negative lookahead assertion

/^(?![^()]*[()][^()]*$)REST_OF_REGEX_HERE/ 

這可以確保不會有在你輸入一個左或右括號。

說明:

^  # Start of string 
(?!  # Assert that it's impossible to match... 
[^()]* # any number of characters other than parentheses, 
[()] # then a single parenthesis, 
[^()]* # then any number of characters other than parentheses, 
$  # then the end of the string. 
)  # End of lookahead 

當然可能還有其他方法可以做到你需要什麼,但你並沒有告訴我們的您正在使用的匹配規則的其餘部分。

1

我的建議是自動格式的數量,同時進入它,請參閱下面

演示

$(function() { 
 

 
    $('#us-phone-no').on('input', function() { 
 

 
    var value = $(this).val(); 
 

 
    var nums = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/); 
 
    var formated = !nums[2] ? nums[1] : nums[1] + '-' + nums[2] + (nums[3] ? '-' + nums[3] : ''); 
 

 
    $(this).val(formated); 
 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="tetx" id="us-phone-no">

相關問題