说好的技术分哈,要给力额,兄弟
答:我们可以用正则表达式来定义复杂的字符串格式,(\d{17}[0-9a-zA-Z]|\d{14}[0-9a-zA-Z])可以用来判断是否为合法的15位或18位身份证号码。
因为15位和18位的身份证号码都是从7位到第12位为身份证为日期类型。这样我们可以设计出更精确的正则模式,使身份证号的日期合法,这样我们的正则模式可以进一步将日期部分的正则修改为[12][0-9]{3}[01][0-9][123][0-9],当然可以更精确的设置日期。
在jdk的java.util.Regex包中有实现正则的类,Pattern和Matcher。以下是实现代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
/**
* @param args
*/
public static void main(String[] args) {
// 测试是否为合法的身份证号码
String[] strs = { "130681198712092019", "13068119871209201x",
"13068119871209201", "123456789012345", "12345678901234x",
"1234567890123" };
Pattern p1 = Pattern.compile("(\\d{17}[0-9a-zA-Z]|\\d{14}[0-9a-zA-Z])");
for (int i = 0; i < strs.length; i++) {
Matcher matcher = p1.matcher(strs[i]);
System.out.println(strs[i] + ":" + matcher.matches());
}
Pattern p2 = Pattern.compile("\\d{6}(\\d{8}).*"); // 用于提取出生日字符串
Pattern p3 = Pattern.compile("(\\d{4})(\\d{2})(\\d{2})");// 用于将生日字符串进行分解为年月日
for (int i = 0; i < strs.length; i++) {
Matcher matcher = p2.matcher(strs[i]);
boolean b = matcher.find();
if (b) {
String s = matcher.group(1);
Matcher matcher2 = p3.matcher(s);
if (matcher2.find()) {
System.out.println("生日为" + matcher2.group(1) + "年"
+ matcher2.group(2) + "月"
+ matcher2.group(3) + "日");
}
}
}
}
}
2、编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。
答:
package cn.itcast;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class MainClass{
public static void main(String[] args) throws Exception{
FileManager a = new FileManager("a.txt",new char[]{'\n'});
FileManager b = new FileManager("b.txt",new char[]{'\n',' '});
FileWriter c = new FileWriter("c.txt");
String aWord = null;
String bWord = null;
while((aWord = a.nextWord()) !=null ){
c.write(aWord + "\n");
bWord = b.nextWord();
if(bWord != null)
c.write(bWord + "\n");
}
while((bWord = b.nextWord()) != null){
c.write(bWord + "\n");
}
c.close();
}
}
class FileManager{
String[] words = null;
int pos = 0;
public FileManager(String filename,char[] seperators) throws Exception{
File f = new File(filename);
FileReader reader = new FileReader(f);
char[] buf = new char[(int)f.length()];
int len = reader.read(buf);
String results = new String(buf,0,len);
String regex = null;
if(seperators.length >1 ){
regex = "" + seperators[0] + "|" + seperators[1];
}else{
regex = "" + seperators[0];
}
words = results.split(regex);
}
public String nextWord(){
if(pos == words.length)
return null;
return words[pos++];
}
} |