How to write a regex for string matches that starts with @ or ends with?

How to write a regular expression for string matches that starts with @ or ends with @ I am looking for code in JavaScript.

+6
source share
3 answers

RegEx solution will 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 just use string functions to get the first and / or last character:

 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); } 
+13
source

For a line starting with @ or ending with a comma, the regex will look like this:

 /^@|,$/ 

Or you could just do this:

 if ((str.charAt(0) == "@") || (str.charAt(str.length - 1) == ",")) { // string matched } 
+10
source
 '@test'.match(/^@.*[^,]$|^[^@].*,$/) // @test '@test,'.match(/^@.*[^,]$|^[^@].*,$/) // null 'test,'.match(/^@.*[^,]$|^[^@].*,$/) // test, 'test'.match(/^@.*[^,]$|^[^@].*,$/) // null 
+1
source

Source: https://habr.com/ru/post/892647/


All Articles