正则表达式在##之间查找字符

时间:2014-11-13 11:45:46

标签: java regex

我的文字如下

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());
        }
    }
}

5 个答案:

答案 0 :(得分:0)

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

试试这个。抓住捕获。查看demo.use g标志或全局匹配。

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

答案 1 :(得分:0)

你可以试试下面的正则表达式,

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

DEMO

答案 2 :(得分:0)

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

试试这个正则表达式

答案 3 :(得分:0)

这似乎就是你要找的东西:

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

Regular expression visualization

或者如果你想修剪白色空间:

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

Regular expression visualization

答案 4 :(得分:0)

还有一个模式可以修剪结果

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

Demo

(               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