您可以使用正则表达式和匹配器来查找您的键和值:
public static void main(String[] args) throws IOException
{
String test = "[(xx)(KEYX)some text]";
Pattern pattern = Pattern.compile("\\(KEY.*\\)");
Matcher matcher = pattern.matcher(test);
matcher.find();
String s = matcher.group(0);
String s1 = test.substring(matcher.end(), test.length() - 1);
System.out.println("" + s + " " + s1);
}
这个输出是:
(KEYX) some text
如果您将字符串更改为"[(xx)(KEYXYYYYYY)some text]",那么它将是:
(KEYXYYYYYY) some text
如果您不想在键周围加上括号:
public static void main(String[] args) throws IOException
{
String test = "[(xx)(KEYXYYYYYY)some text]";
Pattern pattern = Pattern.compile("(?<=\\()KEY.*(?=\\))");
Matcher matcher = pattern.matcher(test);
matcher.find();
String s = matcher.group(0);
String s1 = test.substring(matcher.end() + 1, test.length() - 1);
System.out.println("" + s + " " + s1);
}
输出将是:
KEYXYYYYYY some text
**************************************************** ***************更新********************************** ************************
匹配任何键,而不仅仅是 KEY:
public static void main(String[] args) throws IOException
{
String test = "[(xx)(time.zone1)some text]";
Pattern pattern = Pattern.compile("(?<=\\()[^xy].*(?=\\))");
Matcher matcher = pattern.matcher(test);
matcher.find();
String s = matcher.group(0);
String s1 = test.substring(matcher.end() + 1, test.length() - 1);
System.out.println("" + s + " " + s1);
}
这将输出:
time.zone1 some text
**************************************************** ***********更新************************************** ********
同一字符串中的多个匹配项:
public static void main(String[] args) throws IOException
{
String test = "[(xx)(time1.zone1)some text1]blahblahblah[(xx)(time2.zone2)some text2]";
Pattern pattern = Pattern.compile("(?<=\\()[^xy].*?]");
Matcher matcher = pattern.matcher(test);
while(matcher.find())
{
String s = matcher.group(0);
String s1 = s.substring((s.indexOf(")") + 1), (s.length() - 1));
s = s.substring(0, s.indexOf(")"));
System.out.println("" + s + " " + s1);
}
}
这将输出:
time1.zone1 some text1
time2.zone2 some text2