首页 > 解决方案 > 使用正则表达式从Java中的txt文件中获取引号之间的字符串

问题描述

好的,我意识到那里有很多正则表达式问题,但感谢您抽出宝贵时间

编辑为已解决的代码

https://stackoverflow.com/a/25791942/8926366给出了答案

我有一个带有引号的文本文件,我想将其放入ArrayList<String>. 为此,我正在使用ScannerFile方法,并且我想熟悉正则表达式,因为它似乎是一种非常有效的方法。除了我似乎无法让它正常工作!

我设法拼凑了以下由我了解大约 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 以使所有引号也相同

无论如何,感谢您对此的任何帮助,阅读正则表达式文档让我感到非常头疼

感谢任何回答的人!

标签: javaregex

解决方案


为什么不简单地使用下面的正则表达式?

"(?<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]*?"

推荐阅读