用最普通的方法来解析字符串:
import java.text.MessageFormat;
public class ParseIP2 {
public static void main(String[] args) {
String text = "192.168.10.5[port=21,type=FTP]";
parseAddr(text);
String text2 = "192.168.10.5[port=80]";
parseAddr(text2);
}
public static void parseAddr(String text) {
int leftBraceIndex = text.indexOf('[');
String ipAddr = text.substring(0, leftBraceIndex);
String subStr = text.substring(leftBraceIndex+1, text.length()-1);
String[] strings = subStr.split(",");
String portString = strings[0];
String port = portString.split("=")[1];
String type="HTTP";
if (strings.length == 2) {
String typeString = strings[1];
type = typeString.split("=")[1];
}
String msg = MessageFormat.format("IP地址为{0}的服务器为{1}端口提供的服务为{2}",new Object[] {ipAddr, port, type});
System.out.println(msg);
}
}
判断一个字符串是否是email地址:
public class ParseEmail {
public static void main(String[] args) {
String text = "
[email protected] ";
String text1 = "dskfakj";
String text2 = "@126.com";
System.out.println(validateEmail(text));
System.out.println(validateEmail(text1));
System.out.println(validateEmail(text2));
}
public static boolean validateEmail(String text) {
int atIndex = text.indexOf( '@' );
int dotLastIndex = text.lastIndexOf('.');
//必须含有@和.
if(atIndex<0 || dotLastIndex<0) {
return false;
}
int textLen = text.length();
//不能以@或者.开始或结束
if(atIndex==0 || atIndex==textLen || dotLastIndex==0 || dotLastIndex==textLen) {
return false;
}
//@要在最后一个.之前
if(atIndex>dotLastIndex) {
return false;
}
return true;
}
}
正
则表达式的应用:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class ExpReg {
public static void main(String[] args) {
/*
Pattern p = Pattern.compile("b*g");
Matcher m = p.matcher("bbbbbbg");
boolean b = m.matches();
System.out.println(b);
*/
boolean b = Pattern.matches("b*g","bug");
System.out.println(b);
//从文件路径中提取出文件名(包含后缀)
String regEx = ".+/(.+)$";
String str="c:/dir1/dir2/name.txt";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
if(!m.find()) {
System.out.println("文件路径格式错误");
return;
}
System.out.println(m.group(1));
//判断字符串是否为正确的邮政编码
System.out.println(Pattern.matches("[0-9]{6}","330215"));
System.out.println(Pattern.matches("[0-9]{6}","33015"));
//判断字符串是否为正确的国内电话号码
System.out.println(Pattern.matches("[0-9]{3,4}\\-?[0-9]+","010-95555"));
System.out.println(Pattern.matches("[0-9]{3,4}\\-?[0-9]+","01095555"));
System.out.println(Pattern.matches("[0-9]{3,4}\\-?[0-9]+","95555"));
System.out.println(Pattern.matches("[0-9]{3,4}\\-?[0-9]+","0755-95555"));
System.out.println(Pattern.matches("[0-9]{3,4}\\-?[0-9]+","
[email protected] "));
}
}
正在学习中。。。。