如何使用regexp确保@旁边的字母应该只有字母

时间:2018-12-24 04:59:48

标签: javascript regex

我正在对电子邮件进行正则表达式验证。可以正常工作,但是它允许用户添加@.xyz.com,但这意义不大。我如何确保用户仅应在alphabet符号旁边添加@

在模式中,我添加了[\w\.]是为了在@是出于@some.xx.com目的之后添加的原因。 (用户可以在字母后/内输入。)

$(function(){
 
 $('#email').on('keyup', function(event){
   
   var email = event.target.value;
   var pattern = /^([a-zA-Z]{3,})+@[\w\.]+\.(com|org)$/
   if(!email) return false;
   
   console.log(pattern.test(email));
   
 })
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="email" id="email" value="" />

有人帮我吗?

2 个答案:

答案 0 :(得分:3)

由于import time initial_buy_quantity = 643 initial_buy_price = 1.23 current_buy_price = 1.26 current_sell_price = 1.26 current_profit = (1 - (initial_buy_price / current_sell_price)) * 100 min_profit_percent = 0.5 precision = 3 print("Initial buy quantity " + str(initial_buy_quantity)) print("Initial buy price " + str(initial_buy_price)) print("Current profit %: " + str(current_sell_price)) start_time = time.time() temp_quantity = 0 temp_profit = 0 step = 10 ** (-1 * precision) iters = 0 while temp_profit < min_profit_percent: iters += 1 temp_quantity += step total_quantity = initial_buy_quantity + temp_quantity total_value = (initial_buy_price * initial_buy_quantity) + (current_buy_price * temp_quantity) avg_price = total_value / total_quantity temp_profit = (1 - (initial_buy_price / avg_price)) * 100 print("Iterations: " + str(iters)) print("Duration in seconds: " + str(time.time() - start_time)) print("Max quantity I can buy now and maintain my min profit %: " + str(temp_quantity)) print("Weighted avg price: " + str(avg_price)) print("Profit when buying new quantity: " + str(temp_profit)) 之后的字符必须是单词字符,因此只需在@后加上@加上单词边界。另外请注意,\b不需要在字符集中进行转义,并且可以使用.(不区分大小写)标志,而不必重复i

[a-zA-Z]
$('#email').on('keyup', function(event) {
  var email = event.target.value;
  var pattern = /^([a-z]{3,})+@\b[\w.]+\.(?:com|org)$/i
  if (!email) return false;

  console.log(pattern.test(email));

})

如果您还想确保输入中的<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="email" id="email" value="" />彼此不正确,请重复.而不是字符集:

(?:\w+\.)
$('#email').on('keyup', function(event) {
  var email = event.target.value;
  var pattern = /^([a-z]{3,})+@(?:\w+\.)+(?:com|org)$/i
  if (!email) return false;

  console.log(pattern.test(email));

})

答案 1 :(得分:0)

您正在寻找@后的\w+\.的重复模式,即

const tests = [
  'aaa@.xyz.com',
  'aaa@a.xyz.com',
  'aaa@a..xyz.com',
  'aaa@some.xx.com'
]

tests.forEach(test => {
  console.log(test, /^([a-z]{3,})+@(\w+\.)+(com|org)$/i.test(test));
});