簡體   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