java - 使用正则表达式从Java中的txt文件中获取引号之间的字符串
问题描述
好的,我意识到那里有很多正则表达式问题,但感谢您抽出宝贵时间
编辑为已解决的代码
https://stackoverflow.com/a/25791942/8926366给出了答案
我有一个带有引号的文本文件,我想将其放入ArrayList<String>
. 为此,我正在使用Scanner
和File
方法,并且我想熟悉正则表达式,因为它似乎是一种非常有效的方法。除了我似乎无法让它正常工作!
我设法拼凑了以下由我了解大约 85% 的指南和人民解决方案提供的正则表达式令牌:
(?<=(["']\b))(?:(?=(\\?))\2.)*?(?=\1)
现在我这样理解:
(?<= # positive lookbehind group1
( # for this new group group2
["'] # the characters I am looking for
\b # word boundary anchor
) # end group2
) # end group1
(?: # non-capturing group3
(?= # lookahead group4
(\\?) # I still have no idea what this means exactly
) # end group 4
\2 # matching the contents of the 2nd group in the expression.
) # end group3
*? # lazy
(?=\1) # look ahead for group 1
我现在将确认它不起作用哈哈
然而,这有效(由于我的法语键盘,从 [\"] 中删除了 ' ,将逗号与法语引号分开会太长,在这种情况下没什么大不了的)
([\"])((?:(?=(\\?))\3.)*?)\1
输入:
“有两件事是无限的:宇宙和人类的愚蠢;我不确定宇宙。”
“思想伟大的人,往往会犯很大的错误”——马丁·海德格尔
它给:
有两件事是无限的:宇宙和人类的愚蠢;我不确定宇宙。
思想大的人,往往犯大错
对于所有对为什么他们的正则表达式不适用于 txt 文件感到困惑的人 - 尝试使用 notepad++ 或其他东西来替换所有各种可能的引号(确保检查结束字符和开始字符!)用一种引号
这是方法:(现在效果很好)
public class WitticismFileParser {
ArrayList<String> witticisms;
Scanner scan;
String regex="([\"])((?:(?=(\\\\?))\\3.)*?)\\1"; //"(?s)([\"])((?<quotedText>(?=(\\\\?))\\3.)*?)(?<[\"])";
public ArrayList<String> parse(String FILE_PATH){
witticisms = new ArrayList<>();
Pattern pattern = Pattern.compile(regex);
try{
File txt= new File(FILE_PATH);
scan= new Scanner(txt);
String line="";
Matcher matcher;
matcher=pattern.matcher(line);
while(scan.hasNext()){
line=scan.nextLine();
matcher=matcher.reset(line);
if (matcher.find()){
line=matcher.group(2);
witticisms.add(line);
System.out.println(line);
}
}
}catch(IOException e){
System.err.println("IO Exception- "+ e.getMessage());
e.printStackTrace();
}catch(Exception e){
System.err.println("Exception- "+e.getMessage());
e.printStackTrace();
}finally{
if(scan!=null)
scan.close();
}
return witticisms;
}
}
在这里留下故障排除
当我在扫描仪得到它时直接让它打印线时,我看到输入文本符合预期。我确保重新格式化 .txt 以使所有引号也相同
无论如何,感谢您对此的任何帮助,阅读正则表达式文档让我感到非常头疼
感谢任何回答的人!
解决方案
为什么不简单地使用下面的正则表达式?
"(?<textBetweenQuotes>[\s\S]*?)"
" matches the character " literally.
(?<textBetweenQuotes> is the start of a named capture group.
[\s\S]*? matches any character including newlines between zero or an infinite amount of times but lazily (so stopping as soon as possible).
) is the end of the named capture group.
" matches the character " literally.
如果你不能在你的程序中使用命名的捕获组,你总是可以使用下面的正则表达式而不使用它并替换它的引号。
"[\s\S]*?"
推荐阅读
- php - 我应该如何使用 fpdf 设置 pdf 的下载名称?
- java - ClassNotFoundException : com.mysql.jdbc.Driver 但它在类路径中
- python - 使用脚本自动记事本++编辑csv文件
- css - 如何让元素与它旁边的元素对齐?
- sql-server - 从 mssql 表插入触发器触发 nodejs 函数
- templates - 搜索标签页面上的较早帖子问题
- r - 在 R 中使用 :: 使用管道运算符“%>%”
- image - 检索给定分辨率和中心点的图像的角坐标
- python - 从具有特定 len 的文件单词中提取
- django - Google App Engine 为 ... 记录了一堆新连接,并且客户端关闭了本地连接