英文:
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("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 -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论