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 here
should return [f1,f2,f3,f4] if i pass this text with field = "Foo"
How do i do this cleanly?
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.
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.