1

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?

3 Answers 3

2

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:

"\\@\\{.*?\\}"
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1
//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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.