2 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊
在Java中,你必須對(duì)每一個(gè)向前的斜杠(“\”)進(jìn)行轉(zhuǎn)義處理。圖十不是Java的表示形式,所以我們要在每個(gè)“\”前面加上一個(gè)“\”以免出現(xiàn)編譯錯(cuò)誤。遺憾的是,轉(zhuǎn)義處理過程很容易出現(xiàn)錯(cuò)誤,所以應(yīng)該小心謹(jǐn)慎。你可以首先輸入未經(jīng)轉(zhuǎn)義處理的正則表達(dá)式,然后從左到右依次把每一個(gè)“\”替換成“\\”
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
public class Zhengze {
public static void main(String[] args) throws MalformedPatternException {
PatternCompiler compiler = new Perl5Compiler();
String str = ",,test,,,,test";
String argexp = ".*,{3}.*";
Pattern pattern = compiler.compile(argexp);
PatternMatcher matcher = new Perl5Matcher();
if(matcher.contains(str,pattern)) {
MatchResult result = matcher.getMatch();
for(int n = 0; n < result.length(); n++) {
System.out.println(result.group(n));
}
}else{
System.out.println("nothing");
}
}
}

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
java正則表達(dá)式就是定義某個(gè)固定格式的條件判斷,之后判斷某個(gè)對(duì)象是否符合這個(gè)規(guī)定的格式而出現(xiàn)的。
舉例:
package com;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegex {
public static boolean isboolIP(String ipAddress){
String ip="(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";
Pattern pattern = Pattern.compile(ip);
Matcher matcher = pattern.matcher(ipAddress);
return matcher.matches();
}
/** * @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String ipAddress1 = "10.";
String ipAddress2 = "0.0.0.0";
String ipAddress3 = "255.255.255.255";
String ipAddress4 = "192.168.2.1";
String ipAddress5 = "26445687";
String ipAddress6 = "nihao";
String ipAddress7 = "你好??!";
if(isboolIP(ipAddress1)){
System.out.println("IP正確");
}else{
System.out.println("IP錯(cuò)誤");
} if(isboolIP(ipAddress2)){
System.out.println("IP正確"); }else{
System.out.println("IP錯(cuò)誤");
} if(isboolIP(ipAddress3)){
System.out.println("IP正確"); }else{
System.out.println("IP錯(cuò)誤");
}
if(isboolIP(ipAddress4)){
System.out.println("IP正確"); }else{
System.out.println("IP錯(cuò)誤");
添加回答
舉報(bào)