【问题标题】:Ignore pattern in split()忽略 split() 中的模式
【发布时间】:2022-01-22 09:41:04
【问题描述】:

我想拆分由“|”分隔的字符串。但要忽略具有“|”的字符串值。 查找以下示例:

String s = "Shashank|Sam|Location|20246|India|City in India|USA Country|Location|India Specific 2021|25236|A";

我想将Location|India Specific 2021 视为一个值。

预期输出:

Shashank
Sam
Location
20246
India
City in India
USA Country
Location|India Specific 2021
25236
A

每当我在字符串中找到Location|India 时,我都想忽略其中的|

我尝试过使用

(?<!Location|India)\|

但是输出是

Shashank
Sam
Location|20246
India
City in India
USA Country
Location|India Specific 2021
25236
A

谢谢

【问题讨论】:

  • 但在这种情况下,如果我只有 Location 作为值,它会考虑这一点。像 Shashank|Sam|位置|25643|位置|印度。在这个我也会得到 Location|25643
  • 为什么在Location和其他文本之间构建管道?将状态分配为非分隔符是一个概念错误。来源应该是"Shashank|Sam|Location 20246|India|City in India|USA Country|Location India Specific 2021|25236|A"

标签: java regex split


【解决方案1】:

您可以将此正则表达式与带有嵌套lookbehind的否定前瞻一起使用:

\|(?!(?<=Location\|)India )

RegEx Demo

正则表达式详细信息:

  • \|:匹配一个|
  • (?!: 开始负前瞻
    • (?&lt;=Location\|):确保我们在当前位置之前有Location|
    • India :匹配India
  • ): 结束否定前瞻

【讨论】:

    【解决方案2】:
    (?<!\bLocation)\||\|(?!India\b)
    

    Demo

    此正则表达式匹配前面没有 'Location' 的管道字符 (\|) 或后面没有 'India' 的管道字符 (|)。 (?&lt;!\bLocation) 是一个消极的后视(?!India\b) 是一个否定的前瞻

    'India' 之后的单词边界 (\b) 允许在(例如)'Location|Indiana' 中匹配 '|'(类似于 'Location' 之前的单词边界)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多