سؤال

I have followed the solution below this method , but when it comes to extracting string between the codes, there are errors in the regex pattern or pattern cannot match the section of string

such as

This is a test [url] http://www.google.com.hk [/url] and [img] http://www.abc.com/test.png [/img]

how to get data between quotes in java?

هل كانت مفيدة؟

المحلول

You did not state if you have nested patterns, so here is an example to start you off.

You need to double escape \\ here since \ is also an escape character for strings.

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

See working demo

Regular expression:

\[               '['
[^\]]*           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)
\]               ']'

If you want to be specific on img or url code tags, you could use the following.

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

نصائح أخرى

Here's a regex that assumes that the names of your tags ("bbcodes") consist only of word characters. It also checks that the name of the closing tag matches the name of the opening tag. (This is done by referring to the name of the opening tag by the backrefence \1.)

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

Backreferences:

  1. The name of the opening tag. (e.g., url)
  2. A non-greedy match of all characters between the opening and closing tags.

Here's a demonstration. (Also see the 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() + "]");
        }
    }
}

Expected Result

Match=[http://www.google.com.hk]
Match=[http://www.abc.com/test.png]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top