截取一个字符串里括号内的内容 | 您所在的位置:网站首页 › json怎么取小括号里面 › 截取一个字符串里括号内的内容 |
截取一个字符串里括号内的内容并输出(括号不会嵌套,只需要找到第一对括号即可) 示例: 示例1: hello,(world) 输出:world 示例2:system.crash(error: 100) and will done 输出:error: 100 1. 使用字符串截取 public static String getKuoHaoContent(String str){ //校验输入参数 if(str == null || "".equals(str)){ throw new RuntimeException("字符串不能为空"); } String targetStr = str.substring(str.indexOf("(") + 1, str.indexOf(")")); return targetStr; } 2. 使用正则表达式Pattern pattern = Pattern.compile(“(? strList.add(matcher.group()); } return strList.get(0); } 3.完整demo import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author stormkai * @date 2023/2/20 23:00 */ public class StringCut { public static void main(String[] args) { String str1 = "hello,(world)"; System.out.println(StringCut.getKuoHaoContentByRegex(str1)); String str2 = "system.crash(error: 100) and will done"; System.out.println(StringCut.getKuoHaoContent(str2)); } public static String getKuoHaoContent(String str){ //校验输入参数 if(str == null || "".equals(str)){ throw new RuntimeException("字符串不能为空"); } String targetStr = str.substring(str.indexOf("(") + 1, str.indexOf(")")); return targetStr; } public static String getKuoHaoContentByRegex(String str){ List strList = new ArrayList(); Pattern pattern = Pattern.compile("(? |
CopyRight 2018-2019 实验室设备网 版权所有 |