Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式以查找_Java_Regex - Fatal编程技术网

Java 正则表达式以查找

Java 正则表达式以查找,java,regex,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 lo

我有如下文本

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());
        }
    }
}
试试这个。抓取捕获。请参阅演示。使用g标志或全局匹配


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

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

试试这个正则表达式,这似乎就是你想要的:

([^#]+|#[^#]+#)
或者,如果要修剪空白,请执行以下操作:

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

还有一个要修剪结果的图案

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

您的输入中是否存在\n?[^]+[^]+应该可以。逻辑很好。我知道这是怎么回事。但是有没有一个原因可以解释为什么它在java中对我不起作用?我已经用一个代码示例更新了我的问题。@sethu看不出它不起作用的原因。您可以尝试将其放入分隔符中。
\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