0

I have a String like following:

String text = "This is awesome
               Wait what?
               [[Foo:f1 ]]
               [[Foo:f2]]
               [[Foo:f3]]
               Some texty text
               [[Foo:f4]]

Now, I am trying to write a function:

public String[] getFields(String text, String field){
// do somethng
 }

enter code hereshould return [f1,f2,f3,f4] if i pass this text with field = "Foo"

How do i do this cleanly?

1 Answer 1

3

Use the pattern:

Pattern.compile("\\[\\[" + field + ":\\s*([\\w\\s]+?)\\s*\\]\\]");

and get the values of the first capturing group.


String text = "This is awesome Wait what? [[Foo:f1]] [[Foo:f2]]"
        + " [[Foo:f3]] Some texty text [[Foo:f4]]";

String field = "Foo";

Matcher m = Pattern.compile(
        "\\[\\[" + field + ":\\s*([\\w\\s]+?)\\s*\\]\\]").matcher(text);

while (m.find())
    System.out.println(m.group(1));
f1
f2
f3
f4

You can put all the matches in a List<String> and convert that to an array.

Sign up to request clarification or add additional context in comments.

2 Comments

@Fraz You should have included a case like that in your example. What do you want to extract there? "f3 f1"?
umm yeah.. my hack is text.replaceAll("//s" ,"_"); do what you did.. and then reverting back.. is there a cleaner way?

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.