查找指定字符串,将截取的字符串赋给数组
从一个文本文件1.h中:
#endif /* DEV_CONFIG_H_ */
// init function
//---------am_init-------
char* suit_am_init_NOTCALL_GN_01(void);
//--------am_announce_device--------
//--------am_announce_device-----max_call_number out of range--
char* suit_am_announce_device_MCN_OR_GN_01(void);
//--------am_announce_device-----max_insit_number out of range--
char* suit_am_announce_device_MIN_OR_GN_01(void);
//--------am_announce_device----default_reply_timeout set be 0--
char* suit_am_announce_device_DRT_0_GN_01(void);
//--------am_announce_device---max_credit out of range 8
char* suit_am_announce_device_MC_OR_GN_01(void);
将char* …………………………(void);中间的所有字符串,
例如“suit_am_announce_device_MC_OR_GN_01”...依次截取出来赋给一个数组。
-----------在处理字符串s的时候有问题---------------
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
public class getTCarr
{
public static void main(String[] args)
{
try
{
BufferedReader bf=new BufferedReader(new FileReader("c:/1.h"));
String str=null;
String s=null;
while((str=bf.readLine())!=null)
{
Pattern pattern = Pattern.compile("^char\\*(.*?)\\(void\\);");
Matcher matcher = pattern.matcher(str);
while (matcher.find())
{
s=matcher.group(1);
String[] TCarr=s.split("\n");
for(int i=0;i<TCarr.length;i++)
{
System.out.println(TCarr[i]);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
------解决方案--------------------
这种问题喜欢用正则来处理
Java code
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
List<String> results = new LinkedList<String>();
String str = "#endif /* DEV_CONFIG_H_ */\n" +
"// init function\n" +
"//---------am_init-------\n" +
"char* suit_am_init_NOTCALL_GN_01(void);\n" +
"//--------am_announce_device--------\n" +
"//--------am_announce_device-----max_call_number out of range--\n" +
"char* suit_am_announce_device_MCN_OR_GN_01(void);\n" +
"//--------am_announce_device-----max_insit_number out of range--\n" +
"char* suit_am_announce_device_MIN_OR_GN_01(void);\n" +
"//--------am_announce_device----default_reply_timeout set be 0--\n" +
"char* suit_am_announce_device_DRT_0_GN_01(void);\n" +
"//--------am_announce_device---max_credit out of range 8\n" +
"char* suit_am_announce_device_MC_OR_GN_01(void);";
Pattern pattern = Pattern.compile("char\\*(.+?)\\(void\\)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
results.add(matcher.group(1));
}
for (String s : results) {
System.out.println(s);
}
}
}
------解决方案--------------------
代码逻辑有点错误,你的主体循环每次只能得到一行匹配内容,所以不能在循环内进行处理。
逻辑应该修改为: