您可以使用regex、((?<=#APP_ID\s?:)\s*[^,\s]*)|((?<=#CUSTOMER_ID\s?:)\s*[^,\s]*)。使用 group(1) 获取 APP_ID 的值,使用 group(2) 获取 CUSTOMER_ID 的值。
-
(: 捕获组开始(1)
-
(?<=: 积极后向断言的开始
-
#APP_ID:字符串文字,#APP_ID
-
\s?:可选空格
-
::字符文字,:
-
): 积极的后向断言结束
-
\s*:零个或多个空白字符
-
[^,\s]*:逗号和空格以外的任何字符,任意次数
-
): 捕获组结束(1)
-
|:或者
捕获组(2)的描述类似。
演示:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "blablablablablabla #APP_ID : xxxxxx, #CUSTOMER_ID: yyyyyyyy";
Matcher matcher = Pattern.compile("((?<=#APP_ID\\s?:)\\s*[^,\\s]*)|((?<=#CUSTOMER_ID\\s?:)\\s*[^,\\s]*)")
.matcher(str);
while (matcher.find()) {
String appId = matcher.group(1);
String customerId = matcher.group(2);
if (appId != null && !appId.isBlank())
System.out.println("APP_ID: " + appId);
if (customerId != null && !customerId.isBlank())
System.out.println("CUSTOMER_ID: " + customerId);
}
}
}
输出:
APP_ID: xxxxxx
CUSTOMER_ID: yyyyyyyy
从 Java SE 7 开始,还支持命名捕获组,例如在以下代码中,我将 group(1) 命名为 appId,将 group(2) 命名为 customerId:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "blablablablablabla #APP_ID : xxxxxx, #CUSTOMER_ID: yyyyyyyy";
Matcher matcher = Pattern
.compile("(?<appId>(?<=#APP_ID\\s?:)\\s*[^,\\s]*)|(?<customerId>(?<=#CUSTOMER_ID\\s?:)\\s*[^,\\s]*)")
.matcher(str);
while (matcher.find()) {
String appId = matcher.group("appId");
String customerId = matcher.group("customerId");
if (appId != null && !appId.isBlank())
System.out.println("APP_ID: " + appId);
if (customerId != null && !customerId.isBlank())
System.out.println("CUSTOMER_ID: " + customerId);
}
}
}