我的TXT中的内容是:he1ll2ow3ro4ld
我写的java:
FileReader fr = null;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入文件路径及文件名:");
String str = scanner.nextLine();
try
{
fr = new FileReader(str); char[] chs = new char[14];
int n = fr.read(chs, 0, 14); while (n != -1)
{ n = fr.read(chs);
}
System.out.println(chs);
System.out.println("请输入正则表达式:");
String str2 = scanner.nextLine();
String str1 = String.valueOf(chs); String[] st = str1.split(str2);
for (int i = 0; i < st.length; i++)
{
System.out.println(st[i]);
} } catch (FileNotFoundException e)
{
// e.printStackTrace();
} catch (IOException e)
{
// e.printStackTrace();
} finally
{
try
{
if (fr != null)
fr.close();
} catch (IOException e)
{
e.printStackTrace();
} }
输出的结果是:
请输入文件路径及文件名:
E:\\hello.txt
he1ll2ow3ro4ld
请输入正则表达式:
[23]
he1ll
ow
ro4ld
如何输出2,和3 的位置:
格式是:请输入正则表达式:[2-3]
结果如下:
位置:第2行 第2列 匹配内容:2
位置:第3行 第1列 匹配内容:3
我写的java:
FileReader fr = null;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入文件路径及文件名:");
String str = scanner.nextLine();
try
{
fr = new FileReader(str); char[] chs = new char[14];
int n = fr.read(chs, 0, 14); while (n != -1)
{ n = fr.read(chs);
}
System.out.println(chs);
System.out.println("请输入正则表达式:");
String str2 = scanner.nextLine();
String str1 = String.valueOf(chs); String[] st = str1.split(str2);
for (int i = 0; i < st.length; i++)
{
System.out.println(st[i]);
} } catch (FileNotFoundException e)
{
// e.printStackTrace();
} catch (IOException e)
{
// e.printStackTrace();
} finally
{
try
{
if (fr != null)
fr.close();
} catch (IOException e)
{
e.printStackTrace();
} }
输出的结果是:
请输入文件路径及文件名:
E:\\hello.txt
he1ll2ow3ro4ld
请输入正则表达式:
[23]
he1ll
ow
ro4ld
如何输出2,和3 的位置:
格式是:请输入正则表达式:[2-3]
结果如下:
位置:第2行 第2列 匹配内容:2
位置:第3行 第1列 匹配内容:3
Pattern p = Pattern.compile("[12]");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println("Start:" + m.start() + "\tEnd: " + m.end() + "\tMatch: " + m.group());
}
结果:
Start:2 End: 3 Match: 1
Start:3 End: 4 Match: 1
Start:6 End: 7 Match: 2
Start:7 End: 8 Match: 2