gpt4 book ai didi

java - 多行正则表达式匹配器

转载 作者:行者123 更新时间:2023-11-30 09:53:17 30 4
gpt4 key购买 nike

有内容为输入文件:
XX00002200000
XX00003300000

正则表达式:

(.{6}22.{5}\W)(.{6}33.{5})

在 The Regex Coach(用于正则表达式测试的应用程序)中尝试过,字符串匹配正常。

Java:

        pattern = Pattern.compile(patternString);
inputStream = resource.getInputStream();

scanner = new Scanner(inputStream, charsetName);
scanner.useDelimiter("\r\n");

patternString 是从 .xml 添加为 bean 属性的正则表达式(上面提到的)

Java 失败。

最佳答案

简单的解决方案:".{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 Regex,您可以使用: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;

关于java - 多行正则表达式匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3906180/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com