簡體   English   中英

正則表達式以查找##之間的字符

[英]Regular expression to find characters between ##

我有以下文字

Here is some text #variable name# that goes very long with #another variable name# and 
goes longer #another another variable# and some more.

我想寫一個正則表達式,將文本分成這樣的組

Group 1: Here is some text 
Group 2: #variable name#
Group 3: that goes very long with 
Group 4: #another variable name#
Group 5: and goes longer 
Group 6: #another another variable#
Group 7: and some more

我的嘗試很糟糕。 我無法解決這個問題

(.*?)*(#.*#)*(.*?)*

另外,這需要在Java中工作。

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

import static java.util.regex.Pattern.*;

public class Test {

    public static void main(String[] args) {
        Pattern pattern = compile("(([^#]+)|(#[^#]+#)) ");
        String string="Here is some text #variable name# that goes very long with #another variable name# and " +
                "goes longer #another another variable# and some more.";
        Matcher matcher = pattern.matcher(string);
        while(matcher.find()){
            System.out.println(matcher.group());
        }
    }
}
([^#]+)|(#[^#]+#)

試試看。獲取捕獲。請參閱demo.use g標志或全局匹配。

http://regex101.com/r/pQ9bV3/1

您可以嘗試以下正則表達式,

(#[^#]*#)|\s*(.*?)(?=\s*(?:#|$))

演示

(.*?[^\#])|(#.*#)

試試這個正則表達式

這似乎是您要查找的內容:

([^#]+|#[^#]+#)

正則表達式可視化

或者,如果您要修剪空白:

\s*([^#]+?(?=\s*#|$)|#[^#]+#)

正則表達式可視化

另一種模式可以修剪結果

(#[^#]+#|[^#]+)(?:\s|$)

演示版

(               Capturing Group \1
  #             "#"
  [^#]          Character not in  [^#]
  +             (one or more)(greedy)
  #             "#"
  |             OR
  [^#]          Character not in  [^#]
  +             (one or more)(greedy)
)               End of Capturing Group \1
(?:             Non Capturing Group
  \s            <whitespace character>
  |             OR
  $             End of string/line
)               End of Non Capturing Group

暫無
暫無

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

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