简单的解决方案:".{6}22.{5}\\s+.{6}33.{5}"。请注意,\s+ 是一个 shorthand,用于后续的空白元素。
这是一个例子:
public static void main(String[] argv) throws FileNotFoundException {
String input = "yXX00002200000\r\nXX00003300000\nshort", regex = ".{6}22.{5}\\s+.{6}33.{5}", result = "";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(input);
while (m.find()) {
result = m.group();
System.out.println(result);
}
}
有输出:
XX00002200000
XX00003300000
要玩转 Java 正则表达式,您可以使用:Regular Expression Editor(免费在线编辑器)
编辑:我认为您在读取数据时正在更改输入,请尝试:
public static String readFile(String filename) throws FileNotFoundException {
Scanner sc = new Scanner(new File(filename));
StringBuilder sb = new StringBuilder();
while (sc.hasNextLine())
sb.append(sc.nextLine());
sc.close();
return sb.toString();
}
或者
static String readFile(String path) {
FileInputStream stream = null;
FileChannel channel = null;
MappedByteBuffer buffer = null;
try {
stream = new FileInputStream(new File(path));
channel = stream.getChannel();
buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0,
channel.size());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return Charset.defaultCharset().decode(buffer).toString();
}
导入如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;