Skip to content
欢迎扫码关注公众号

Java 使用正则表达式匹配字符串中半角括号中间的所有内容

使用 PatternMatcher 匹配字符串中 () 之间的内容。示例代码如下:

java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

System.out.println("==================== start ====================");
String ua = "Mozilla/5.0 (Linux; Android 11; M2102K1C Build/RKQ1.201112.002; wv) " +
        "AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.210 " +
        "Mobile Safari/537.36 hap/1.10/xiaomi org.hapjs.mockup/1.10.0.0 " +
        "me.liujiajia.app.sample/1.3.1 ({\"packageName\":\"org.hapjs.mockup\"," +
        "\"type\":\"other\",\"extra\":{}})";
Matcher matcher = Pattern.compile("(?<=\\()[^\\)]+").matcher(ua);
while (matcher.find()) {
    String group = matcher.group();
    System.out.println(group);
}
System.out.println("===================== end =====================");

运行结果如下:

bash
==================== start ====================
Linux; Android 11; M2102K1C Build/RKQ1.201112.002; wv
KHTML, like Gecko
{"packageName":"org.hapjs.mockup","type":"other","extra":{}}
===================== end =====================

正则表达式 (?<=\\()[^\\)]+ 可以分为三个部分:

bash
(?<=\\()[^\\)]+
|--1---||-2--|3|
  1. (?<=\\()
  2. [^\\)]
  3. +

各部分的详细说明:

  1. (?<=\\()
    (?<=pattern)反向肯定预查,其对应的为 正向肯定预查 (?=pattern) ,两者本身都不参与匹配,但是会作为匹配的一个边界,反向肯定预查 可以理解为 开始边界正向肯定预查 则是 结束边界
    这里是 反向肯定预查 ,也就是 开始边界 ,边界值为 \\( ,代表了一个半角左括号,也就是说从一个半角左括号开始匹配
  2. [^\\)]
    []中括号表达式 ,只匹配处于正则表达式中该位置的单个字符,这里为 \\) 也就是半角右括号(其中 \\ 是用来转义为 \ ,再结合 \) 转义为半角右括号)
    ^中括号表达式 种表示查找不在列表或范围内的所有字符,这里就是这种情况,表示匹配不为 ) 的字符
  3. +
    + 表示匹配前面的子表达式一次或多次,这里表示匹配不为 ) 的多个字符,直到 ) 出现

综上,(?<=\\()[^\\)]+ 表示匹配从 ( 开始到第一个 ) 截至的中间的所有字符。从上面实例的打印结果可以看到成功的匹配到了三段。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.