有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在REGEX'或'(|)条件下在其他单词中精确匹配一个单词

我知道有类似的问题,但似乎没有一个符合我的要求。我对regex还不熟悉,还在学习。我非常感谢您对以下问题的帮助
我有以下输入json数据。PS:为了更好地理解我的问题,我简化了实际数据
一,

{
  "name": "abc",
  "response": {
    "postback": "UNIQUE-a651-95e4834b63cc",
    "text": "testing"
  },
  "remarks": "get keyword"
}
{
  "name": "abc",
  "response": {
    "postback": "a651-95e4834b63cc",
    "text": "testing"
  },
  "remarks": "get keyword"
}

正则表达式

(UNIQUE)|(\"(response|someothedata|otherdata|somedata)\")

我想知道这些关键词中哪一个匹配。在这里,如果存在“唯一”字段,它会变得更加棘手,它应该就停在那里,不再匹配
我正在使用以下java代码

pattern = Pattern.compile("(UNIQUE)|(\"(response|someothedata|otherdata|somedata)\")")  
Matcher matcher = pattern.matcher(message);  
if(matcher.find()){
  match = matcher.group();
}  

对于输入json和匹配器。group()返回“response”

我想实现以下目标:

1。group()返回“UNIQUE”
两个人。仅当“唯一”不存在时才返回“响应”

注意:一旦我得到了匹配的单词(match),就没有什么动作可以做了,所以这是不能妥协的

有谁能帮我确定“独特”关键字的优先级吗


共 (1) 个答案

  1. # 1 楼答案

    你可以用

    Pattern pattern = Pattern.compile(".*(UNIQUE|\"(?:response|someothedata|otherdata|somedata)\")");
    Matcher matcher = pattern.matcher(message);  
    if(matcher.find()){
      match = matcher.group(1).replaceAll("^\"|\"$", "");
    }  
    

    regex demo。详情:

    • .*-尽可能多地使用除换行符以外的任何零个或多个字符(这会将正则表达式索引移动到字符串/行的末尾)
    • (UNIQUE|\"(?:response|someothedata|otherdata|somedata)\")-第1组:UNIQUE",然后是responsesomeothedataotherdata 或者somedata然后"

    您正在匹配一个模式的单个匹配项,这意味着匹配项是第一个匹配项还是最后一个匹配项对您来说并不重要。这就是为什么在一个捕获组中添加.*和分组UNIQUE"(?:response|someothedata|otherdata|somedata)"会起作用的原因。唯一的“问题”是response等字的两端都会有双引号,所以你可以用.replaceAll("^\"|\"$", "")安全地删除它们