package com.xiangqiao.Analysis;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AnalysisWord {
public void Analysis(String str) {
System.out.println("--------------字母-------------");
String result="";
String tmp="";
for (int i = 0; i < str.length(); i++) {
Pattern pattern = Pattern.compile("[A-Za-z]");
Matcher matcher = pattern.matcher(str.charAt(i) + "");
if (matcher.matches()) {
result=result+str.charAt(i);
}else{
tmp=result;
result="";
}
if(!tmp.equals("")){
System.out.println(tmp);
tmp="";
}
}
System.out.println("--------------数字-------------");
for (int i = 0; i < str.length(); i++) {
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(str.charAt(i) + "");
if (matcher.matches()) {
result=result+str.charAt(i);
}else{
tmp=result;
result="";
}
if(!tmp.equals("")){
System.out.println(tmp);
tmp="";
}
}
System.out.println("--------------运算符-------------");
for (int i = 0; i < str.length(); i++) {
Pattern pattern = Pattern.compile("[+ - * / = >]");
Matcher matcher = pattern.matcher(str.charAt(i) + "");
if (matcher.matches()) {
result=result+str.charAt(i);
}else{
tmp=result;
result="";
}
if(!tmp.equals("")){
System.out.println(tmp);
tmp="";
}
}
System.out.println("--------------界符-------------");
for (int i = 0; i < str.length(); i++) {
Pattern pattern = Pattern.compile("[( ) { } ;]");
Matcher matcher = pattern.matcher(str.charAt(i) + "");
if (matcher.matches()) {
result=result+str.charAt(i);
}else{
tmp=result;
result="";
}
if(!tmp.equals("")){
System.out.println(tmp);
tmp="";
}
}
}
}
package com.xiangqiao.main;
import com.xiangqiao.Analysis.AnalysisWord;
import com.xiangqiao.file.FileUtil;
public class MainClass {
public static void main(String[] args) {
String result=new FileUtil().ReadFile("my.txt");
System.out.println(result);
new AnalysisWord().Analysis(result);
}
}
package com.xiangqiao.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileUtil {
public String ReadFile(String filePath) {
String result ="";
try {
// 注意路径的写法,java默认的路径是到根目录下
File f = new File(filePath);
if (f.isFile() && f.exists()) {
// 进行编码转换,避免出现乱码
InputStreamReader read = new InputStreamReader(
new FileInputStream(f), "utf-8");
BufferedReader br = new BufferedReader(read);
String line ="";
while ((line = br.readLine()) != null) {
result = result+line;
}
read.close();
} else {
System.out.println("文件读取失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return result;
}
}
}