【问题标题】:RegEx for removing everything before and after a delimiterRegEx 用于删除分隔符前后的所有内容
【发布时间】:2019-10-11 06:59:25
【问题描述】:
我正在尝试使用正则表达式删除两个 | 分隔符前后的所有内容。
一个例子是:
EM|CX-001|Test Campaign Name
并抓取除CX-001 之外的所有内容。我不能使用子字符串,因为管道前后的字符数可能会发生变化。
我尝试使用正则表达式(?<=\|)(.*?)(?=\-),但是虽然这选择了CX-001,但我需要选择除此之外的所有其他内容。
我该如何解决这个问题?
【问题讨论】:
标签:
regex
regex-negation
regex-lookarounds
regex-group
regex-greedy
【解决方案1】:
你可以试试下面的正则表达式:
(^[^|]*\|)|(\|[^|]*$)
String input = "EM|CX-001|Test Campaign Name";
System.out.println(
input.replaceAll("(^[^|]*\\|)|(\\|[^|]*$)", "")
); // prints "CX-001"
正则表达式的解释:
NODE EXPLANATION
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[^|]* any character except: '|' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
\| '|'
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
\| '|'
--------------------------------------------------------------------------------
[^|]* any character except: '|' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of
the string
--------------------------------------------------------------------------------
) end of \2
【解决方案2】:
- 查找:
^[^|]*\|([^|]+).+$
- 替换:
$1
【解决方案3】:
如果您的字符串中只有 2 个管道,您可以匹配第一个管道或从最后一个管道匹配到字符串末尾:
^.*?\||\|.*$
说明
-
^.*?\| 从非贪婪的字符串开始匹配到第一个管道
-
|或者
-
\|.*$ 从最后一个管道到字符串末尾匹配
Regex demo
或者您也可以使用否定字符类 [^|]* 而无需捕获组:
^[^|]*\||\|[^|]*$
Regex demo
注意
在您的模式(?<=\|)(.*?)(?=\-) 中,我认为您的意思是,如果您想在 2 个管道之间进行选择,最后一个正向前瞻应该是 (?=\|) 而不是 -。