簡體   English   中英

RegEx用於刪除定界符之前和之后的所有內容

[英]RegEx for removing everything before and after a delimiter

我正在嘗試刪除兩個之前和之后的所有內容| 使用正則表達式的定界符。

一個例子是:

EM|CX-001|Test Campaign Name

並抓住除CX-001以外的所有東西。 我不能使用子字符串,因為管道前后的字符數可能會發生變化。

我嘗試使用正則表達式(?<=\\|)(.*?)(?=\\-) ,但是雖然這選擇了CX-001 ,但我需要選擇除此以外的所有內容。

我該如何解決這個問題?

  • 查找: ^[^|]*\\|([^|]+).+$
  • 更換: $1

如果字符串中只有2個管道,則可以匹配第一個管道,也可以從最后一個管道匹配到字符串末尾:

^.*?\||\|.*$

說明

  • ^.*?\\| 從字符串非貪心開始到第一個管道匹配
  • | 要么
  • \\|.*$從最后一個管道匹配到字符串結尾

正則表達式演示

或者,您也可以使用否定的字符類[^|]*而不需要捕獲組:

^[^|]*\||\|[^|]*$

正則表達式演示

注意

在您的模式中(?<=\\|)(.*?)(?=\\-)我想您的意思是,如果要在2個管道之間進行選擇,則最后一個正向前行應為(?=\\|)而不是-

您可以嘗試以下正則表達式:

(^[^|]*\|)|(\|[^|]*$)
    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM