2016-09-28 14 views

回答

2

您需要爲此使用lookaheads。考慮這個正則表達式:

^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]+$ 

它有2個強迫出現數字和字母表的前瞻。

(?=.*[0-9]) # assert that there is at least a digit ahead 
(?=.*[a-zA-Z]) # assert that there is at least an alphabet ahead 
[a-zA-Z0-9]+$ # will match only alphanumerics 

Regex Lookaround Reference

請注意,如果您正則表達式工具/語言不支持向前看符號,那麼你將不得不使用交替

^[a-zA-Z0-9]*?([0-9][a-zA-Z0-9]*[a-zA-Z]|[a-zA-Z][a-zA-Z0-9]*[0-9])[a-zA-Z0-9]*$ 
+0

注意,這也將讓&&密碼1,雖然我只想強制字母和數字。 –

+0

噢那麼在這種情況下讓我更新正則表達式 – anubhava

+0

使用什麼anubhava張貼,這是否工作? '^([0-9] [A-ZA-Z] |?[A-ZA-Z] [0-9])[\ W \ d] * $' – sdexp

相關問題