截取一個字符串里括號內(nèi)的內(nèi)容并輸出(括號不會嵌套,只需要找到第一對括號即可)
示例:
示例1: hello,(world) 輸出:world
示例2:system.crash(error: 100) and will done 輸出:error: 100
1. 使用字符串截取
public static String getKuoHaoContent(String str){
//校驗輸入?yún)?shù)
if(str == null || "".equals(str)){
throw new RuntimeException("字符串不能為空");
}
String targetStr = str.substring(str.indexOf("(") + 1, str.indexOf(")"));
return targetStr;
}
2. 使用正則表達(dá)式
Pattern pattern = Pattern.compile(“(?<=\()[^\)]+”);是獲取所有小括號里面的內(nèi)容文章來源:http://www.zghlxwxcb.cn/news/detail-505317.html
public static String getKuoHaoContentByRegex(String str){
List<String> strList = new ArrayList<>();
Pattern pattern = Pattern.compile("(?<=\\()[^\\)]+");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
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){
//校驗輸入?yún)?shù)
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<String> strList = new ArrayList<>();
Pattern pattern = Pattern.compile("(?<=\\()[^\\)]+");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
strList.add(matcher.group());
}
return strList.get(0);
}
}
輸出結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-505317.html
world
error: 100
到了這里,關(guān)于截取一個字符串里括號內(nèi)的內(nèi)容的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!