【问题标题】:how to match exactly one word among the others in REGEX 'or'(|) condition如何在 REGEX 'or'(|) 条件中精确匹配一个单词
【发布时间】:2021-01-31 04:05:49
【问题描述】:

我知道有类似的问题,但似乎没有一个符合我的要求。我是正则表达式的新手,仍在学习。感谢您对以下问题的任何帮助。
我有以下输入 json 数据。 PS:为了更好地理解我的问题,我已经简化了实际数据。
1.

{
  "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,matcher.group() 返回 'response'

我想实现以下目标:

为 1. group() 返回 'UNIQUE'
2.返回“响应”,即仅当“唯一”不存在时

注意:一旦我得到匹配的词(匹配),就几乎没有基于此的操作,所以不能妥协

谁能帮助我如何以某种方式优先考虑“唯一”关键字?

【问题讨论】:

    标签: java json regex


    【解决方案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 或 ",后跟 response、someothedata、otherdata 或somedata 然后"

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

    【讨论】:

    • 感谢您理解需求并给出解决方案。但是有一个问题,这仅在输入 json 为单行时才有效。我已经更新了问题,请查看Regex demo。 ps:对不起,我应该正确地提到输入数据。
    • @SavinayaShetty 使用"(?s).*(UNIQUE|\"(?:response|someothedata|otherdata|somedata)\")"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多