[英]Need help writing a regex pattern
I am trying to find a pattern in a string that has a value that starts with ${
and ends with }
. 我试图在字符串中找到一个模式,该模式的值以
${
开头,以}
结尾。 There will be a word between the curly brackets, but I won't know what word it is. 大括号之间将有一个单词,但我不知道它是什么单词。
This is what I have \\$\\\\{[a-zA-Z]\\\\}
这就是我的
\\$\\\\{[a-zA-Z]\\\\}
${a}
works, but ${aa}
doesn't. ${a}
有效,但${aa}
无效。 It seems it's only looking for a single character. 似乎只在寻找一个字符。
I am unsure what I am doing wrong, or how to fix it and would appreciate any help anyone can provide. 我不确定自己在做错什么,或如何解决它,希望任何人都能提供帮助。
I think this could help you 我认为这可以帮助您
var str = "The quick brown ${fox} jumps over the lazy ${dog}"; var re = /\\$\\{([az]+)\\}/gi; var match; while (match = re.exec(str)) { console.log(match[1]); }
Click Run code snippet and check your developer console for output 点击运行代码段,然后检查您的开发者控制台的输出
"fox"
"dog"
Explanation 说明
+
means match 1 or more of the previous term — in this example, match 1 or more of [az]
+
表示匹配上一项的1个或多个-在此示例中,匹配[az]
1个或多个 (...)
parentheses will "capture" the match so you can actually do something with it — in my example, I'm just using console.log
to output it (...)
括号将“捕获”匹配项,因此您实际上可以使用它—在我的示例中,我只是使用console.log
输出它 i
modifier (at the end of the regexp) means perform a case- i nsensitive match i
改性剂(在正则表达式的结尾)指执行一个区分我 nsensitive匹配 g
modifier means match all instances of this regexp in the target string g
修饰符表示匹配目标字符串中此正则表达式的所有实例 while
loop will continue running for each match that re.exec
finds. re.exec
找到的每个匹配项, while
循环将继续运行。 Once re.exec
cannot match another instance, it will return null
and the loop will exit. re.exec
无法匹配另一个实例,它将返回null
并退出循环。 Additional information 附加信息
Try console.log(match)
using the code above. 使用上面的代码尝试
console.log(match)
。 Each match comes with other useful information such as the string index where the match occurred 每个匹配项都附带其他有用的信息,例如匹配发生的字符串索引
Gotchas 陷阱
This will not work for nested ${} sets
这不适用于嵌套的$ {}集
For example, this regexp will not work on "The quick brown ${fox jumps ${over}} the lazy ${dog}."
例如,此正则表达式不适用于
"The quick brown ${fox jumps ${over}} the lazy ${dog}."
A good website for regex reference and testing is http://rubular.com/ 一个用于正则表达式参考和测试的好网站是http://rubular.com/
It looks like you need to add a +, which tells the regex to look for one or more of a character. 看来您需要添加一个+,告诉正则表达式查找一个或多个字符。
Try: \\${[a-zA-Z]+}
试试:
\\${[a-zA-Z]+}
You're close! 你近了!
All you need is to use a +
to tell the expression that there will be one or more of whatever was just before it (in this case [a-zA-Z]
) like this: 您所需要做的就是使用
+
告诉表达式,在它之前将有一个或多个(在本例中为[a-zA-Z]
),如下所示:
\${[a-zA-Z]+}
You need to use *
( zero or more ) or +
( one or more ). 您需要使用
*
( 零个或多个 )或+
( 一个或多个 )。 So this [a-zA-Z]
would be [a-zA-Z]+
, meaning 1 or more letters. 因此,此
[a-zA-Z]
为[a-zA-Z]+
,表示1个或多个字母。 The entire regex would look like: 整个正则表达式如下所示:
\$\{[a-zA-Z]+\}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.