Java Regex:匹配任何单词单词,并且必须包含一定的作品,但除了一个单词

时间:2019-01-08 02:01:26

标签: java regex

我需要一个Java正则表达式来匹配除某个单词以外的任何单词,同时包含另一个单词。

例如,字符串不能包含Apple,但必须包含Peach

Apple and Peach - Not match
Peach and Apple- Not match
Peach - Match 
Three Peach - Match 
Peach is good - Match 
Peach is good, but Apple is bad - Not match

Apple Peach不能出现在字符串中。

到目前为止,我已经获得了这段代码。

^(?!(?:Apple)$)Peach$

2 个答案:

答案 0 :(得分:2)

您应该使用<div class="wrapper"> <h1>Line One</h1> <div class="breaker"></div> <p>Line Two</p> </div>来匹配字符串开头和要查找的关键字之间的任何字符:

.*

演示:https://regex101.com/r/t3Dz4E/1

答案 1 :(得分:2)

如果要匹配整个句子,则应使用以下正则表达式:

typedef unsigned char UINT8;
typedef unsigned char BYTE;  
typedef unsigned long int UINT32; 
#define S_LCB_100 0xF0BB12DE;
#define MULTI 0x1A;
volatile static BYTE Counter = 0;
static UINT8 Loop = 0;    
static UINT32 List[]=  
{
    S_LCB_100,
    0x00000000,
};
while(( 0x00000000 != List[Loop] ) && ( 0 != Counter ))
{
 .......some code
}
if ( List[Loop] == 0x00000000 )
{
.....some code
} 

演示: https://regex101.com/r/G6RdPO/2/

如果大小写无关,则可以将正则表达式更改为:

^(?!.*Apple).*Peach.*$

最后但并非最不重要的一点是,您对(?i)^(?!.*Apple).*Peach.*$ peachesapples(包含pineapples)应该如何处理尚不清楚。如果您不想考虑它们,请使用:

apple

演示: https://regex101.com/r/G6RdPO/5

(?i)^(?!.*\bApple\b).*\bPeach\b.*$

如果您还希望将其复数考虑在内:

Apple and Peach - Not match
Peach and Apple- Not match
Peach - Match 
Three Peach - Match 
Peach is good - Match 
Peach is good, but Apple is bad - Not match
Nothing - Not match
Peaches are good - Not match
Apples an Peaches - Not match
Pineapple and Peach - Match

演示: https://regex101.com/r/G6RdPO/4

(?i)^(?!.*\bApple(?:s)?\b).*\bPeach(?:es)?\b.*$