2012-11-28 67 views
0

我想匹配我的字符串到一個或另一個序列,它必須至少匹配其中的一個。如何在正則表達式中提供OR運算符?

對於and我瞭解到它是可以做到的:

(?=one)(?=other) 

有沒有這樣的事情對於OR?

我正在使用Java,Matcher和Pattern類。

+0

退房這個職位 的http://計算器。com/questions/2031805/java-regular-expression-or-operator –

回答

4

一般來說約的正則表達式,你一定要開始你的旅程到正則表達式仙境這裏:Regex tutorial

目前需要的是什麼|(管道字符)

要匹配字符串one OR other,使用方法:

(one|other) 

,或者如果你不想存儲的比賽,只是簡單

one|other 

Java的具體this article is very good at explaining the subject

你將不得不使用你的模式是這樣的:

//Pattern and Matcher 
Pattern compiledPattern = Pattern.compile(myPatternString); 
Matcher matcher = pattern.matcher(myStringToMatch); 
boolean isNextMatch = matcher.find(); //find next match, it exists, 
if(isNextMatch) { 
    String matchedString = myStrin.substring(matcher.start(),matcher.end()); 
} 

請注意,有關於Matcher然後我顯示的內容更多的可能性這裏...

//String functions 
boolean didItMatch = myString.matches(myPatternString); //same as Pattern.matches(); 
String allReplacedString = myString.replaceAll(myPatternString, replacement) 
String firstReplacedString = myString.replaceFirst(myPatternString, replacement) 
String[] splitParts = myString.split(myPatternString, howManyPartsAtMost); 

另外,我強烈推薦使用Regexplanet (Java)refiddle(這不包含Java特定檢查器)等在線正則表達式檢查程序,它們讓您的生活變得更輕鬆!

+0

您的鏈接都不鏈接到特定於Java的信息。特別是refiddle根本不提供Java信息 –

+0

@Brian謝謝,我也意識到了這一點,在它上面工作 – ppeterka

2

「或」運算符拼寫爲|,例如one|other

所有的運營商列在documentation

1

你可以用這樣一個管分離:

Pattern.compile("regexp1|regexp2"); 

了幾個簡單的例子見here

0

使用|字符OR

Pattern pat = Pattern.compile("exp1|exp2"); 
Matcher mat = pat.matcher("Input_data");