...java)we(!)Ssdf";现在我要截取括号里面的。
发布网友
发布时间:2024-03-04 10:25
我来回答
共5个回答
热心网友
时间:2024-03-08 09:19
用substring
热心网友
时间:2024-03-08 09:22
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SubStringStr {
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<String, String>();
String str = "abc(hello)sdf(java)we(!)Ssdf";
// 直接使用“()”截取
String[] infos = str.split("\\(");
for (int i = 1; i <infos.length; i++) {
String ss[] = infos[i].split("\\)");
map1.put(i + "", ss[0]);
}
Set<String> set1 = map1.keySet();
for (String string : set1) {
//System.out.println(string + " " + map1.get(string));
}
//使用pattern
Map<String, String> map2 = new HashMap<String, String>();
String regex = "abc(.*?)sdf(.*?)we(.*?)Ssdf";
System.out.println(regex);
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if(m.find()){
map2.put("1", m.group(1));
map2.put("2", m.group(2));
map2.put("3", m.group(3));
}
Set<String> set2 = map2.keySet();
for (String string : set2) {
//System.out.println(string + " " + map2.get(string));
}
}
}
热心网友
时间:2024-03-08 09:18
Map<String, String> map = new HashMap<String, String>();
String str = "abc(hello)sdf(java)we(!)Ssdf";
int index = 1;
while ((str.indexOf("(")>0)&&(str.indexOf(")")>0))
{
int i=str.indexOf("(");
int y=str.indexOf(")");
String Str1=str.substring(i+1,y);
map.put(index+"", Str1);
str=str.substring(y+1,str.length());
index++;
}
热心网友
时间:2024-03-08 09:21
String str = "abc(hello)sdf( java)we(!)Ssdf";
Map<String, String> map = new HashMap<String, String>();
Pattern p = Pattern.compile("\\([\\w\\!\\s]+\\)");
Matcher m = p.matcher(str);
int index = 1;
String value = "";
while (m.find())
{
value = m.group().replace("(", "");
value = value.replace(")", "");
map.put(String.valueOf(index), value);
index++;
}
System.out.println(map);
热心网友
时间:2024-03-08 09:16
import java.util.*;
public class Test {
public static void main(String[] args) {
//如果你不懂泛型,可以把<>及其里面的内容都去掉
String str = "abc(hello)sdf( java)we(!)Ssdf";
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, str.substring(4, 9));
map.put(2, str.substring(14, 19));
map.put(3, str.substring(23, 24));
//遍历HashMap集合
Set<Integer> set = map.keySet();
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
System.out.print(map.get(it.next()));
}
}
}
遍历结果:hello java!
利用正则表达式更简单