Glory to Russia
Glory to Russia

Reputation: 18710

Java regex: Parsing a string with two matching substrings

I have following string

task BLABLA@{taskId} "@{BLABLA.title}"

and want to extract all placeholders from it.

Placeholders are @{taskId} and @{BLABLA.title}.

I use following code:

final Pattern pattern = Pattern.compile(".*(\\@\\{.*?\\}).*");
final Matcher matcher = pattern.matcher(this.text);

while (matcher.find())
{
    final String placeholder = matcher.group(1);
    this.placeholders.add(placeholder);
}

The problem is that in lines with more than one placeholder (like shown above) it detects only the first placeholder.

Another example:

task BLABLA@{taskId} "@{BLABLA.title}" { start @{startDateTime}

task BLABLA2 "Text" { allocate RBLABLA2 effort @{BLABLA2.effort} } }

In this text, the code above detects

  1. @{BLABLA.title}
  2. @{startDateTime}
  3. @{BLABLA2.effort}

If I remove @{BLABLA.title}, then @{taskId} is detected.

How should I modify the code so that in the last example, all placeholders (@{taskId}, @{BLABLA.title}, @{startDateTime}, @{BLABLA2.effort}) are detected?

Upvotes: 1

Views: 1554

Answers (3)

Delta
Delta

Reputation: 547

//Another way to solve problem
String task = "task BLABLA@{taskId} \"@{BLABLA.title}";
String splitBy = "\\@\\{";
String[] splitted = task.split( splitBy );
Set<String> placeHolders = new HashSet<String>();
for( String split : splitted ) {
  int startOf = split.indexOf("}");
  if( startOf != -1 ) {
     placeHolders.add(split.substring( 0, startOf));
  }
 }
 System.out.println("place holders are " + placeHolders);

Upvotes: 1

Guillaume Polet
Guillaume Polet

Reputation: 47607

Remove the leading and ending .* because they eat your whole string. In your loop replace m.group(1) by m.group(0)

Upvotes: 1

Lukas Eder
Lukas Eder

Reputation: 221076

Remove the greedy wildcard matches (.*) at the beginning and end of the expression. Your regex would then read:

"(\\@\\{.*?\\})"

Having removed the wildcards, you can also omit grouping:

"\\@\\{.*?\\}"

Upvotes: 2

Related Questions