如何在bbcodes之间获取字符串

时间:2013-11-26 15:22:18

标签: java regex bbcode

我已按照此方法下面的解决方案,但在提取代码之间的字符串时,正则表达式模式或模式中的错误无法匹配字符串部分

,例如

  

这是一项测试[url] http://www.google.com.hk [/url][img] http://www.abc.com/test.png [/img]

how to get data between quotes in java?

2 个答案:

答案 0 :(得分:2)

你没有说明你是否有嵌套模式,所以这里有一个例子让你开始。

你需要在这里加倍转义\\,因为\也是字符串的转义字符。

String s = "This is a test [url] http://www.google.com.hk [/url]\n"
         + " and [img] http://www.abc.com/test.png [/img]";

Pattern p = Pattern.compile("\\[[^\\]]*\\]([^\\]]*)\\[[^\\]]*\\]");
Matcher m = p.matcher(s);
while (m.find()) {
  System.out.println(m.group(1).trim());
}

请参阅working demo

正则表达式:

\[               '['
[^\]]*           any character except: '\]' (0 or more times)
 \]              ']'
(                group and capture to \1:
 [^\]]*          any character except: '\]' (0 or more times)
)                end of \1
\[               '['
 [^\]]*          any character except: '\]' (0 or more times)
\]               ']'

如果您想要对imgurl代码标记具体说明,可以使用以下内容。

Pattern p = Pattern.compile("(?i)\\[(?:url|img)\\]([^\\]]*)\\[\\/(?:url|img)\\]");

答案 1 :(得分:1)

这是一个正则表达式,它假设您的代码(“bbcodes”)的名称只包含单词字符。它还会检查结束标记的名称是否与开始标记的名称匹配。 (这是通过backrefence \1引用开始标记的名称来完成的。)

\[(\w+)\](.+?)\[/\1\]
   ^^^    ^^^
    1      2

反向引用:

  1. 开始标记的名称。 (例如,url
  2. 开始和结束标记之间所有字符的非贪婪匹配。
  3. 这是一个演示。 (另请参阅live demo。)

    import java.util.*;
    import java.util.regex.*;
    
    class RegexTester
    {
        public static void main (String[] args)
        {
            String s =
                  "This is a test [url] http://www.google.com.hk [/url]\n"
                + " and [img] http://www.abc.com/test.png [/img]";
    
            Pattern p = Pattern.compile("\\[(\\w+)\\](.+?)\\[/\\1\\]");
    
            Matcher m = p.matcher(s);
            while (m.find()) {
                System.out.println("Match=[" + m.group(2).trim() + "]");
            }
        }
    }
    

    预期结果

    Match=[http://www.google.com.hk]
    Match=[http://www.abc.com/test.png]