簡體   English   中英

正則表達式匹配兩個字符串之間的所有字符

[英]Regex Match all characters between two strings

示例:“這只是一個簡單的句子”。

我想匹配“這是”和“句子”之間的每個字符。 應該忽略換行符。 我無法弄清楚正確的語法。

例如

(?<=This is)(.*)(?=sentence)

正則表達式

我使用了lookbehind (?<=)和lookbehind ( (?=)以便匹配中不包含“This is”和“sentence”,但這取決於您的用例,您也可以簡單地寫This is(.*)sentence

這里重要的是您激活正則表達式引擎的“dotall”模式,以便. 匹配換行符。 但是你如何做到這一點取決於你的正則表達式引擎。

接下來的事情是如果你使用.*.*? . 第一個是貪婪的,將匹配到字符串中的最后一個“句子”,第二個是惰性的,將匹配到字符串中的下一個“句子”。

更新

正則表達式

This is(?s)(.*)sentence

(?s) 打開 dotall 修飾符的位置,使. 匹配換行符。

更新 2:

(?<=is \()(.*?)(?=\s*\))

與您的示例“這是(一個簡單的)句子”相匹配。 Regexr上看到這里

需要惰性量詞

重新提出這個問題,因為接受答案中的正則表達式對我來說似乎不太正確。 為什么? 因為

(?<=This is)(.*)(?=sentence)

將匹配my first sentence. This is my second my first sentence. This is my second句話, This is my first sentence. This is my second sentence. This is my first sentence. This is my second sentence.

見演示

您需要兩個外觀之間的惰性量詞。 添加一個? 讓明星變得懶惰。

這符合你想要的:

(?<=This is).*?(?=sentence)

見演示 我刪除了不需要的捕獲組。

跨換行符匹配的 DOTALL 模式

請注意,在演示中設置了“點匹配換行符模式”(又名)點全部(請參閱如何以各種語言打開 DOTALL )。 在許多正則表達式風格中,您可以使用在線修飾符(?s)對其進行設置,將表達式轉換為:

(?s)(?<=This is).*?(?=sentence)

參考

試試This is[\s\S]*?sentence ,適用於 javascript

這個:

This is (.*?) sentence

適用於 javascript。

使用這個: (?<=beginningstringname)(.*\n?)(?=endstringname)

這對我有用(我正在使用VS Code ):

for: This is just\na simple sentence

使用: This.+ sentence

你可以簡單地使用這個: \This is.*? \sentence \This is.*? \sentence

正則表達式使用 Java 方法匹配兩個字符串之間的所有內容。

List<String> results = new ArrayList<>(); //For storing results
String example = "Code will save the world";

讓我們使用 Pattern 和 Matcher 對象來使用 RegEx (. ?)*

Pattern p = Pattern.compile("Code "(.*?)" world");   //java.util.regex.Pattern;
Matcher m = p.matcher(example);                      //java.util.regex.Matcher;

由於 Matcher 可能包含多個匹配項,因此我們需要遍歷結果並將其存儲。

while(m.find()){   //Loop through all matches
   results.add(m.group()); //Get value and store in collection.
}

此示例將僅包含“將保存”一詞,但在較大的文本中可能會找到更多匹配項。

如果有人在 Jenkins 上下文中尋找這樣的例子。 它解析 build.log,如果找到匹配項,則生成匹配項失敗。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

node{    
    stage("parse"){
        def file = readFile 'build.log'

        def regex = ~"(?s)(firstStringToUse(.*)secondStringToUse)"
        Matcher match = regex.matcher(file)
        match.find() {
            capturedText = match.group(1)
            error(capturedText)
        }
    }
}

我在這里搜索正則表達式以在 Python2 中的 print"string" 之間轉換此打印語法,在舊腳本中使用:print("string"),對於 Python3。 效果很好,否則使用 2to3.py 進行額外的轉換。 這是我對其他人的解決方案:

在 Regexr.com 上嘗試一下(由於某種原因在 NP++ 中不起作用):

find:     (?<=print)( ')(.*)(')
replace: ('$2')

對於變量:

(?<=print)( )(.*)(\n)
('$2')\n

對於 label 和變量:

(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n

如何用 Python3 的 print("string") 替換 Python2 中的所有 print"string"?

有一種方法可以處理文本塊中這種拆分的重復實例嗎? 例如:“這只是一個簡單的句子。這里有一些額外的東西。這只是一個簡單的句子。這里還有一些東西。這只是一個簡單的句子。”。 要匹配每個實例而不是整個字符串,請使用以下代碼:

data = "This is just\na simple sentence. Here is some additional stuff. This is just\na simple sentence. And here is some more stuff. This is just\na simple sentence."

pattern = re.compile('This is (?s).*? sentence')

for match_instance in re.finditer(pattern, data):
    do_something(match_instance.group())

在 JavaScript 的情況下,您可以使用[^] 匹配任何字符,包括換行符

使用帶有點的/s標志. 匹配任何字符也可以,但適用於整個模式,並且 JavaScript 不支持內聯修飾符來打開/關閉標志。

為了盡可能少地匹配字符,您可以通過附加問號使量詞不貪婪,並使用捕獲組來提取介於兩者之間的部分。

This is([^]*?)sentence

請參閱regex101 演示

作為旁注,要不匹配部分單詞,您可以使用諸如\bThissentence\b之類的單詞邊界

 const s = "This is just\na simple sentence"; const regex = /This is([^]*?)sentence/; const m = s.match(regex); if (m) { console.log(m[1]); }


JavaScript 中的環視變體是(?<=This is)[^]*?(?=sentence)並且您可以檢查JS 正則表達式中的 Lookbehind 以獲得支持。

另請參閱關於 Lookbehind 的重要說明

 const s = "This is just\na simple sentence"; const regex = /(?<=This is)[^]*?(?=sentence)/; const m = s.match(regex); if (m) { console.log(m[0]); }

我是這樣做的:
這對我來說比試圖找出必要的特定正則表達式更容易。

int indexPictureData = result.IndexOf("-PictureData:");
int indexIdentity = result.IndexOf("-Identity:");
string returnValue = result.Remove(indexPictureData + 13);
returnValue = returnValue + " [bytecoderemoved] " + result.Remove(0, indexIdentity); ` 

要在 VIM 中快速搜索,您可以在 Vim 控制提示符處使用:/This is.*\_.*sentence

我有這個字符串

      headers:
        Date:
          schema:
            type: string
            example: Tue, 23 Aug 2022 11:36:23 GMT
        Content-Type:
          schema:
            type: string
            example: application/json; charset=utf-8
        Transfer-Encoding:
          schema:
            type: string
            example: chunked
        Connection:
          schema:
            type: string
            example: keep-alive
        Content-Encoding:
          schema:
            type: string
            example: gzip
        Vary:
          schema:
            type: string
            example: Accept-Encoding
        Server:
          schema:
            type: number
            example: Microsoft-IIS/10.0
        X-Powered-By:
          schema:
            type: string
            example: ASP.NET
        Access-Control-Allow-Origin:
          schema:
            type: string
            example: '*'
        Access-Control-Allow-Credentials:
          schema:
            type: boolean
            example: 'true'
        Access-Control-Allow-Headers:
          schema:
            type: string
            example: '*'
        Access-Control-Max-Age:
          schema:
            type: string
            example: '-1'
        Access-Control-Allow-Methods:
          schema:
            type: string
            example: GET, PUT, POST, DELETE
        X-Content-Type-Options:
          schema:
            type: string
            example: nosniff
        X-XSS-Protection:
          schema:
            type: string
            example: 1; mode=block
      content:
        application/json:

我想從標題中刪除所有內容headers:content ,所以我寫了這個正則表達式(headers:)[^]*?(content)

它按預期工作,發現該表達式發生了多少次。

崇高的文字 3x

在崇高的文本中,您只需寫下您有興趣保留的兩個單詞,例如在您的情況下它是

“這是”和“句子”

你寫。*在兩者之間

This is.* sentence

這應該對你有好處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM