Javascript 如何为以@ 开头或以, 结尾的字符串匹配编写正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6674951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a regex for string matches which starts with @ or end with ,?
提问by sushil bharwani
How to write a regex for string matches which starts with @
or end with ,
. I am looking for a code in JavaScript.
如何为@
以,
.开头或结尾的字符串匹配编写正则表达式。我正在寻找 JavaScript 代码。
回答by Salman A
RegEx solution would be:
正则表达式解决方案是:
var rx = /(^@|,$)/;
console.log(rx.test("")); // false
console.log(rx.test("aaa")); // false
console.log(rx.test("@aa")); // true
console.log(rx.test("aa,")); // true
console.log(rx.test("@a,")); // true
But why not simply use string functions to get the first and/or last characters:
但是为什么不简单地使用字符串函数来获取第一个和/或最后一个字符:
var strings = [
"",
"aaa",
"@aa",
"aa,",
"@a,"
];
for (var i = 0; i < strings.length; i++) {
var string = strings[i],
result = string.length > 0 && (string.charAt(0) == "@" || string.slice(-1) == ",");
console.log(string, result);
}
回答by jfriend00
For a string that either starts with @ or ends with a comma, the regex would look like this:
对于以@ 开头或以逗号结尾的字符串,正则表达式如下所示:
/^@|,$/
Or you, could just do this:
或者你,可以这样做:
if ((str.charAt(0) == "@") || (str.charAt(str.length - 1) == ",")) {
// string matched
}
回答by TheBrain
'@test'.match(/^@.*[^,]$|^[^@].*,$/) // @test
'@test,'.match(/^@.*[^,]$|^[^@].*,$/) // null
'test,'.match(/^@.*[^,]$|^[^@].*,$/) // test,
'test'.match(/^@.*[^,]$|^[^@].*,$/) // null