我想匹配我的字符串到一個或另一個序列,它必須至少匹配其中的一個。如何在正則表達式中提供OR運算符?
對於and
我瞭解到它是可以做到的:
(?=one)(?=other)
有沒有這樣的事情對於OR?
我正在使用Java,Matcher和Pattern類。
我想匹配我的字符串到一個或另一個序列,它必須至少匹配其中的一個。如何在正則表達式中提供OR運算符?
對於and
我瞭解到它是可以做到的:
(?=one)(?=other)
有沒有這樣的事情對於OR?
我正在使用Java,Matcher和Pattern類。
一般來說約的正則表達式,你一定要開始你的旅程到正則表達式仙境這裏: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特定檢查器)等在線正則表達式檢查程序,它們讓您的生活變得更輕鬆!
您的鏈接都不鏈接到特定於Java的信息。特別是refiddle根本不提供Java信息 –
@Brian謝謝,我也意識到了這一點,在它上面工作 – ppeterka
「或」運算符拼寫爲|
,例如one|other
。
所有的運營商列在documentation。
使用|
字符OR
Pattern pat = Pattern.compile("exp1|exp2");
Matcher mat = pat.matcher("Input_data");
的答案已經給出,使用管道 '|'運營商。除此之外,它可能是有用的,以測試在一個正則表達式測試你的正則表達式,而無需運行你的應用程序,例如:
退房這個職位 的http://計算器。com/questions/2031805/java-regular-expression-or-operator –