簡體   English   中英

使用正則表達式搜索文本

[英]Search for text with Regex

我需要一個正則表達式來使文本從句子中的[]之間移出。

示例文字:

Hello World - Test[**This is my string**]. Good bye World.

預期結果:

**This is my String**

我想出的正則表達式是Test\\\\[[a-zA-Z].+\\\\] ,但這返回了整個**Test[This is my string]**

您可以使用捕獲組來訪問感興趣的文本:

\[([^]]+)\]

使用JavaScript的概念的快速證明:

var text = 'Hello World - Test[This is my string]. Good bye World.'
var match = /\[([^\]]+)\]/.exec(text)
if (match) {
  console.log(match[1]) // "This is my string"
}

如果您使用的正則表達式引擎同時支持lookaheadlookbehind ,則Tim的解決方案更為合適。

Match m = Regex.Match(@"Hello World - Test[This is my string]. Good bye World.", 
            @"Test\[([a-zA-Z].+)\]");
Console.WriteLine(m.Groups[1].Value);
(?<=Test\[)[^\[\]]*(?=\])

應該做你想做的。

(?<=Test\[) # Assert that "Test[" can be matched before the current position
[^\[\]]*    # Match any number of characters except brackets
(?=\])      # Assert that "]" can be matched after the current position

閱讀有關環視斷言的信息

暫無
暫無

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

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