简体   繁体   English

正则表达式获取字符和空格之间的字符串并排除第一个分隔符

[英]Regex to get the string between a character and a whitespace and excluding the first delimiter

In the following text what Regex (Javascript) would match "user" (user is a random name), excluding the "@" character?在下面的文本中,正则表达式(Javascript)将匹配“用户”(用户是一个随机名称),不包括“@”字符?

I want to tag this @user here
and this @user
@user


I have looked at the following solutions and made the following regexes that did not work我查看了以下解决方案并制作了以下无效的正则表达式

RegEx pattern to match a string between two characters, but exclude the characters 正则表达式模式匹配两个字符之间的字符串,但排除字符

\@(.*)\s

Regular Expression to find a string included between two characters while EXCLUDING the delimiters 正则表达式查找包含在两个字符之间的字符串,同时排除分隔符

(?!\@)(.*?)(?=\s)

Regex: Matching a character and excluding it from the results? 正则表达式:匹配一个字符并将其从结果中排除?

^@[^\s]+

Finally I made this regex that works but returns "@user" instead of "user":最后我做了这个正则表达式,但返回“@user”而不是“user”:

@[^\s\n]+

The Javascript used to execute the regex is:用于执行正则表达式的 Javascript 是:

string.match(/@[^\s\n]+/)

I see I need to post a clarification.我看到我需要发布说明。

If one knows a pattern beforehand in JS, ie if you do not build a regex from separate variables, one should be using a RegExp literal notation (eg /<pattern>/<flag(s)> ).如果事先知道 JS 中的一种模式,即如果您不从单独的变量构建正则表达式,则应该使用RegExp文字符号(例如/<pattern>/<flag(s)> )。

In this case, you need a capturing group to get a submatch from a match that will start with a @ and go on until the next non-whitespace character.在这种情况下,您需要一个捕获组来从匹配中获取子匹配,该匹配将以@开头并继续直到下一个非空白字符。 You cannot use String#match if you have multiple values inside one input string, as global regexps with that method lose the captured texts.如果在一个输入字符串中有多个值,则不能使用String#match ,因为使用该方法的全局正则表达式会丢失捕获的文本。 You need to use RegExp#exec :您需要使用RegExp#exec

 var s = "I want to tag this @user here\\nand this @user\\n@user"; var arr = []; var re = /@(\\S+)\\b/g; while ((m=re.exec(s)) !== null) { arr.push(m[1]); } document.write(JSON.stringify(arr));

The regex I suggest is @(\\S+)\\b :我建议的正则表达式是@(\\S+)\\b

  • @ - matches a literal @ @ - 匹配文字@
  • (\\S+) - matches and captures into Group 1 one or more non-whitespace characters that finish with (\\S+) - 匹配并捕获到第 1 组的一个或多个以
  • \\b - word boundary (remove if you have Unicode letters inside the names). \\b - 单词边界(如果名称中有 Unicode 字母,请删除)。

If you execute it this way, it should work:如果您以这种方式执行它,它应该可以工作:

var str = "I want to tag this @user here";
var patt = new RegExp("@([^\\s\\n]+)");
var result = patt.exec(str)[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM