Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 looking for a code in JavaScript.

like image 929
sushil bharwani Avatar asked Jul 13 '11 06:07

sushil bharwani


2 Answers

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);
}
like image 156
Salman A Avatar answered Oct 13 '22 01:10

Salman A


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
}
like image 43
jfriend00 Avatar answered Oct 13 '22 01:10

jfriend00