开发者

How to write a regex for string matches which starts with @ or end with ,?

How to write a regex for string matches which starts with @ or end with ,. I am loo开发者_运维问答king for a code in JavaScript.


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);
}


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
}


'@test'.match(/^@.*[^,]$|^[^@].*,$/) // @test
'@test,'.match(/^@.*[^,]$|^[^@].*,$/) // null
'test,'.match(/^@.*[^,]$|^[^@].*,$/) // test,
'test'.match(/^@.*[^,]$|^[^@].*,$/) // null
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜