如何从字符串中提取所有括号内的值并单行输出?
Extract All Values Inside Parentheses from a String
Ah, I see the issue—StringUtils.substringBetween() only returns the first occurrence of text between the start and end delimiters, which is why you're only getting "for". To get all the values inside parentheses, here are two straightforward solutions:
Using Apache Commons Lang's StringUtils (since you're already using this library)
The substringBetweenAll() method is exactly what you need—it returns an array of all substrings between the specified delimiters. You can then join this array into a single string with spaces:
import org.apache.commons.lang3.StringUtils; public class ParenthesisExtractor { public static void main(String[] args) { String str = "java programming (for)all (beginners) is (very) interesting"; String[] parenthesizedValues = StringUtils.substringBetweenAll(str, "(", ")"); // Join the array elements with spaces String result = String.join(" ", parenthesizedValues); System.out.println(result); // Output: for beginners very } }
Using Standard Java (no external libraries)
If you prefer not to rely on Apache Commons Lang, you can use regular expressions to find all matches:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParenthesisExtractor { public static void main(String[] args) { String str = "java programming (for)all (beginners) is (very) interesting"; // Regex to match text inside parentheses: \\( captures the opening (, (.*?) captures non-greedy text, \\) captures closing ) Pattern pattern = Pattern.compile("\\((.*?)\\)"); Matcher matcher = pattern.matcher(str); StringBuilder resultBuilder = new StringBuilder(); while (matcher.find()) { if (resultBuilder.length() > 0) { resultBuilder.append(" "); // Add space between values } resultBuilder.append(matcher.group(1)); // Get the captured text inside parentheses } System.out.println(resultBuilder.toString()); // Output: for beginners very } }
Both approaches will give you the desired output: for beginners very.
内容的提问来源于stack exchange,提问作者Modest
相关产品推荐
相关产品推荐

