正则表达式之间匹配文本

时间:2011-11-11 15:39:47

标签: javascript regex

我得到的字符串如下:

"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'。

什么是正则表达式?

4 个答案:

答案 0 :(得分:5)

编辑,以防你有更多而不是其中一个字,并希望迭代它们。 *自问题发生变化后再次编辑。*

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 «\/»

答案 1 :(得分:1)

var string = "some other likehere/dhsad huasdhuas huadssad/h ah as/";
var matches = string.match(/[/](.*)[/]/)[1];

应该这样做。

修改EDIT以符合新标准。

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

如果要在同一字符串中匹配多个匹配项,则需要使用exec。请参阅@FailedDev's answer

相关问题