упоминание пользователя в тексте - PullRequest
3 голосов
/ 15 апреля 2019

Здесь у меня есть строка с пользователем @mention, но я не хочу считать пользователей с пробелом, точкой, запятой, дефисом.

var str= `Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham. 
@portpofili.9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393
@portpofili-9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393`;
var pattern = /@\b[-?(\w+)?]+\b/gi;
var count = (str.match(pattern) || []).length;
console.log(count);

Здесь результат 10, но мне нужно 8. Как я могу это сделать?Заранее спасибо

Ответы [ 2 ]

5 голосов
/ 15 апреля 2019

Ваше регулярное выражение необходимо изменить:

@ [^ \ s -.] + (= \ S |? $)

@, за которым следует что-либо, не являющееся., - или пробел, пока следующий символ не станет пробелом или концом ввода.

var str= `Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham. 
@portpofili.9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393
@portpofili-9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393`;
var pattern = /@[^.\s-]+(?=\s|$)/gi;
var count = (str.match(pattern) || []).length;
console.log(count);
1 голос
/ 15 апреля 2019

Ваш шаблон [-?(\w+)?] состоит из класса символов, который соответствует любому из перечисленных символов (который также может быть записан как [-+?()\w]

То, что вы могли бы сделать, это сопоставить символы в 1+ слов и утверждать, что то, что находится прямо справа, не является непробельным символом \S с использованием отрицательного взгляда (?!:

@\w+(?!\S)

Regex demo

var str= `Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham. 
@portpofili.9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393
@portpofili-9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393`;
var pattern = /@\w+(?!\S)/gi;
var count = (str.match(pattern) || []).length;
console.log(count)

Если предшествующее может быть только началом строки или пробелом, вы можете сопоставить его, используя чередование, и записать @mention в группе:

(?:^|\s)(@\w+)(?!\S)

var str = `Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
@portpofili.9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393
@portpofili-9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393 @portpofili.9393@portpofili9394 @@test`;
var pattern = /(?:^|\s)(@\w+)(?!\S)/gi;
var count = (str.match(pattern) || []).length;
console.log(count);

Пример получения значений из группы:

var pattern = /(?:^|\s)(@\w+)(?!\S)/gi;
const str = `@test
@portpofili.9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393
@portpofili-9393 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393

@portpofili.9393-j @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393
@portpofili-9393-8 @portpofili9394 @portpofili9395 @portpofili9393 @portpofili9393

@portpofili.9393@portpofili9394
@@test

@testing`;
let m;
while ((m = pattern.exec(str)) !== null) {
  if (m.index === pattern.lastIndex) {
    pattern.lastIndex++;
  }
  console.log(m[1]);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...