繁体   English   中英

正则表达式之间的匹配文本

[英]regex match text in between

我得到像这样的字符串:

"some text here /word/ asdhd"
"some other likehere/word1/hahas"
"some other likehere/dhsad huasdhuas huadssad/h ah as/"

我需要获得两个斜线之间的字符串,即“ word”,“ word1”,“ dhsad huasdhuas huadssad”和“ h ah as”。

正则表达式是什么?

进行编辑,以防您有多个单词中的一个并且想要遍历它们。 *由于问题已更改,请再次编辑。*

var myregexp = /\/(.+?)(?=\/)/g;
var match = myregexp.exec(subject);
while (match != null) {

        // matched text: match[1]

    match = myregexp.exec(subject);
}

说明:

    // \/(.+?)(?=\/)
// 
// 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];

那应该做。

编辑进行了修改以匹配新标准。

\/[a-zA-Z0-9]+\/

\\ /匹配斜杠
[a-zA-Z0-9]匹配任何大写或小写字母,以及任何数字
+表示一个或多个

"some text here /word/ asdhd".match(/\/(.+)\//)

如果要在同一字符串中匹配多个匹配项,则需要使用exec 参见@FailedDev的答案

暂无
暂无

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

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