好的,我知道那里有很多正则表达式问题,但感谢您花时间
编辑为已解决的代码
https://stackoverflow.com/a/25791942/8926366拿着答案
我有一个包含引号的文本文件,我想将其放入 ArrayList<String>
中.为此,我使用 Scanner
和 File
方法,我想熟悉正则表达式,因为它看起来是一种非常有效的方法。当然,我似乎无法让它工作!
我设法拼凑了以下正则表达式 token ,由我理解大约 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]*?"
关于java - 使用正则表达式从Java中的txt文件中获取引号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55524551/