簡體   English   中英

正則表達式提取“與”和“或”以及介於兩者之間的單詞

[英]Regex to extract 'and' and 'or' and words in between

示例文本:

field1=value1field2=[field2Value]field3=field3Value

我想分開購買:

  • field1=value1
  • and
  • field2=[field2Value]
  • or
  • field3=field3Value

請注意,文本不能以“或”或“和”開頭/結尾,例如,這些文本應失敗

例1: and field1=field1Value

例如:2 field1=field1Value and

這是我到目前為止所得到的https://regex101.com/r/TEQujk/1

不確定是否要

(?<=^|\band\b|\bor\b) *\b(.*?)\b *(?=$|\band\b|\bor\b)|\b(and|or)\b

基本上,此模式匹配兩種不同的情況:

  • and / or (以及字符串的開始/結尾)周圍的字符串
  • and or自己

給定abc and def or ghi的樣本

  • 第一場比賽,第1組: abc
  • 第2場比賽,第2組: and
  • 第三局,第一組: def
  • 第4場比賽,第2組: or
  • 第5場比賽,第1組: ghi

說明

第一部分

(?<=^|\band\b|\bor\b) *\b(.*?)\b *(?=$|\band\b|\bor\b)
(?<=                )                                   lookbehind
    ^                                                   start of line
     |\band\b                                           or "and" as a whole word
             |\bor\b                                    or "or" as a whole word
                    ) *                                 follow by some spaces
                       \b(.*?)\b                        bunch of words (match as few as possible)
                                  *                      follow by some space
                                    (?=                ) lookahead group
                                       $|\band\b|\bor\b  end of line OR and OR or

或第二部分:

|\b(and|or)\b       OR and/or as a whole word

上面的正則表達式僅用於從字符串中提取單個令牌的目的。 因此它與您的WHOLE字符串不匹配(供您檢查有效性)

您應該具有檢查令牌是否有意義的邏輯,或者可以簡單地檢查一個單獨的正則表達式,如下所示:

^(\w+(\s+and\s+|\s+or\s+))*(\w+)$

我們可以通過一次調用String#split()來做到這一點,只要看到和和/或,就使用不消耗的環顧方法。 請注意,我在匹配項上調用String#trim() ,因為沒有使用空格。

String input = "field1=value1 and field2=[field2Value] or field3=field3Value";
String[] parts = input.split("(?=\\s+(and|or))|(?<=(and|or)\\s+)");
for (String part : parts) {
    System.out.println(part.trim());
}

field1=value1
and 
field2=[field2Value]
or 
field3=field3Value

演示版

class Main {
  public static void main(String[] args) {
    String str="field1=value1 and field2=[field2Value] or field3=field3Value";
    String test[]=str.split("(?=and|or*+)|(\\s)");
    for (String str1:test)
    {
      if(!str1.equals(""))
      System.out.println(str1);
    }
  }
}

輸出:

field1=value1
and
field2=[field2Value]
or
field3=field3Value

如果值和等號之間沒有空格,並且所需參數之間始終有空格,則可以簡單地使用

inputString.split("\\s+");

暫無
暫無

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

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