简体   繁体   中英

Regular expression to match a string between @@ in Java

I am using Java Pattern Compile to match substring with a specific pattern and add it to a List.

I want Regular expression to match the following scenarios

  1. String starts and ends with (eg @@foo,bar,bla@@)
  2. String starts with "@@ and ends with @@"
  3. String starts with Hello "@@ and ends with @@", World
  4. String starts with Hello "@@ and ends with @@",// This is a comment

The current code is:-

    List<String> matches = new ArrayList<String>();
    Matcher m = Pattern.compile("@@([^@@]*)@@")
                 .matcher(content);
        System.out.println(m.find());
        while (m.find()) {
            matches.add(m.group());
    }

My content is '<script> var bookSrc = "@@book:URL@@",var books_count: @@Count@@, var active = true</script>'

The above code only matches the strings between @@ and the actual result is [@@count@@] and I expect the result to be [@@book:URL@@, @@count@@]

Any help would be appreciated, how should I modify my pattern to accommodate all of the above scenarios.

You call Matcher.find once before the loop is executed. Thererfore the first match is skipped. If you remove

System.out.println(m.find());

it works as expected. You can still test, if there were matches after the loop:

System.out.println(!matches.isEmpty());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM