[英]regex match text in between
I get strings like: 我得到像这样的字符串:
"some text here /word/ asdhd"
"some other likehere/word1/hahas"
"some other likehere/dhsad huasdhuas huadssad/h ah as/"
What I need is to get the string between the two slashes, 'word', 'word1', 'dhsad huasdhuas huadssad' and 'h ah as'. 我需要获得两个斜线之间的字符串,即“ word”,“ word1”,“ dhsad huasdhuas huadssad”和“ h ah as”。
What is a regex for that? 正则表达式是什么?
Edit in case you have more than one of those words and want to iterate through them. 进行编辑,以防您有多个单词中的一个并且想要遍历它们。 *Edit again since question was changed.*
*由于问题已更改,请再次编辑。*
var myregexp = /\/(.+?)(?=\/)/g;
var match = myregexp.exec(subject);
while (match != null) {
// matched text: match[1]
match = myregexp.exec(subject);
}
Explanation : 说明:
// \/(.+?)(?=\/)
//
// Match the character “/” literally «\/»
// Match the regular expression below and capture its match into backreference number 1 «(.+?)»
// Match any single character that is not a line break character «.+?»
// Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\/)»
// Match the character “/” literally «\/»
var string = "some other likehere/dhsad huasdhuas huadssad/h ah as/";
var matches = string.match(/[/](.*)[/]/)[1];
That should do it. 那应该做。
\/[a-zA-Z0-9]+\/
\\/ matches slashes \\ /匹配斜杠
[a-zA-Z0-9] matches any letters uppercase or lower, and any numbers [a-zA-Z0-9]匹配任何大写或小写字母,以及任何数字
+ means one or more +表示一个或多个
"some text here /word/ asdhd".match(/\/(.+)\//)
If you want to match more than one occurence in the same string, you need to use exec
. 如果要在同一字符串中匹配多个匹配项,则需要使用
exec
。 See @FailedDev's answer . 参见@FailedDev的答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.