【问题标题】:Regex Get all concordances正则表达式 获取所有索引
【发布时间】:2013-03-24 14:51:21
【问题描述】:

我需要获取包含此文本的所有字符串 %variables% 这里有一些文字 %/variables%

例子

%enca% something here %variables% take this text %/variables% 
other stuffs here, I dont need this 
%variables% I need this too %/variables%
other stuffs, etc

我拥有的是这样的:

我试试这个:
%variables%(.*?)%/variables%

像这样工作(只有一场比赛)

http://regexr.com?34cge

但在 Java 中不起作用:

private boolean variablesTag(String s)
    {
    Pattern pattern = Pattern.compile("/%variables%(.*?)%/variables%/gs");
    Matcher matcher = pattern.matcher(s);

    while (matcher.find()) {
     //do some stuff...stored, work with the string, etc...
    };

    return true;
}

如果你能告诉我把绳子拿进去的方法,我真的很感激。 我想要的是这样的:

收下这段文字 这也是

我正在使用 NetBeans...

解决方案

Pattern pattern = Pattern.compile("%variables%(.*?)%/variables%",Pattern.MULTILINE|Pattern.DOTALL);

没有标志是行不通的

【问题讨论】:

    标签: java regex match


    【解决方案1】:

    在 Java 中,您不需要正则表达式上的“/”分隔符,实际上使用它们是不正确的。如果你想在正则表达式中添加标志,Pattern.compile 有两个参数版本(参见API docs)。

    改变

    Pattern pattern = Pattern.compile("/%variables%(.*?)%/variables%/gs");
    

    例如:

    Pattern pattern = Pattern.compile("%variables%(.*?)%/variables%", Pattern.DOTALL);
    

    然后在循环中使用matcher.group(1) 访问捕获的内容。

    【讨论】:

    • +1 正确。关于斜线,与其说“你不需要它们”,不如说它们与正则表达式无关——它们是一种应用程序语言语法结构。
    【解决方案2】:

    尝试使用这种模式:-

    Pattern.compile("%variables%(.*?)%/variables%");
    

    然后像这样获取所需的值。选择你想要的。

    while(matcher.find()){
            System.out.println(matcher.group()); //Prints this "%variables% take this text %/variables%"
            System.out.println(matcher.group(1)); //Prints this " take this text"
    }
    

    【讨论】:

    • 没有标志不起作用,我认为是因为文本包含回车,无论如何,非常感谢您的时间,我很感激
    【解决方案3】:
    public static void main(String... args) {
    
        String input = "%enca% something here %variables% take this text %/variables% "
                + "other stuffs here, I dont need this"
                + "%variables% I need this too %/variables%"
                + "other stuffs, etc";
    
        Pattern pattern = Pattern.compile("%variables%(.*?)%/variables%");
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            String s = matcher.group(1);
            System.out.format("%s\n", s);
        }
    }
    

    输出

     take this text 
     I need this too 
    

    【讨论】:

    • 没有标志不起作用,我认为是因为文本包含回车,无论如何,非常感谢您的时间,我很感激
    • Crashman,“字符串输入”中没有 CR。您是否尝试按原样复制我的样本?我猜你做到了,但是..它应该可以工作..
    • 我只是尝试在每个 [+ "] 之后添加 "\r\n" 和 "\n" - 也可以。
    • 你是完全正确的,你的代码工作,但我真的不知道为什么我的文本不能工作,这里又是 = "%inicio% %encabezado% %variables% %float, var1,10% %/variables% %variables% %int,var1,10% %/variables% %/encabezado% %/inicio%" 本文来自jTextArea
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 2011-03-31
    • 2013-05-07
    • 1970-01-01
    相关资源
    最近更新 更多