使用正则表达式请求用户的家庭地址。

huangapple go评论90阅读模式
英文:

Asking user for home address using Regex

问题

function button1() {
let address = prompt("请输入您的地址");
var regex = /[\d+[ ](?:[A-Za-z0-9.-]+[ ]?)+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St).?]/;

if (regex.test(address)) {
return true;
} else {
console.log("请输入有效地址");
return false;
}
}

英文:

I want to make a prompt asking a user for a valid home address using regex.

I have tested the regex im using on regex101.com but the code still doesnt work no matter what I write...

Example of address that should pass: 26 John Street, City Road

What have I done wrong?

function button1() {
let address = prompt("Please enter your address");
var regex = /[\d+[ ](?:[A-Za-z0-9.-]+[ ]?)+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St).?]/;

  if (regex.test(address)) {
    return true;
  } else {
    console.log("Please enter a valid address");
    return false;

  }
}

答案1

得分: 0

我认为你不应该将整个表达式放在 []

这会导致它不是一个一个接一个地期望的符号序列,而是一组替代项(我认为这不是你的意图)。

所以尝试这样:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function button1() {
  //  let address = prompt("Please enter your address");
  const address = "26 John Street, City Road"

  var regex = /\d+[ ](?:[A-Za-z0-9.-]+[ ]?)+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St).?/;

  if (regex.test(address)) {
    console.log("Valid")
    return true;
  } else {
    console.log("Please enter a valid address");
    return false;
  }
}

button1()

<!-- end snippet -->
英文:

I think you shouldn't have the whole expression inside [ and ]

That causes it not to be a sequence of symbols to be expected one-after-the-other, but rather a set of alternatives (which I don't think is what you intended).

So try this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function button1() {
  //  let address = prompt(&quot;Please enter your address&quot;);
  const address = &quot;26 John Street, City Road&quot;

  var regex = /\d+[ ](?:[A-Za-z0-9.-]+[ ]?)+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St).?/;

  if (regex.test(address)) {
    console.log(&quot;Valid&quot;)
    return true;
  } else {
    console.log(&quot;Please enter a valid address&quot;);
    return false;

  }
}

button1()

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月26日 19:28:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75571654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定