【问题标题】:regex for parse sentences with skipping the parenthesis contents用于解析带有跳过括号内容的句子的正则表达式
【发布时间】:2012-08-11 18:33:29
【问题描述】:

我需要一个句子解析器。解析器根据白色字符拆分完整的句子。并且它将括号内的完整内容视为一个单词(已解析的单词)。

输入句子:-

“这是很棒的工作(我真正的工作)。”

需要输出:-

This 

is 

the 

work

(my real job)

which 

is 

great.

【问题讨论】:

  • 不,不是,这是我想在我的一个项目工作中实现的东西
  • 你应该更清楚输入行。这似乎很容易解释。

标签: java regex parsing


【解决方案1】:

不确定是否有一种很好的方法可以使用此正则表达式从类似的句子中解析出单词。无论如何,您可能需要遍历句子。我不认为String.split() 会为你做这件事。只需编写一个循环来为您执行此操作,然后您就可以处理括号不匹配时的细节。例如,这将假设所有内容都是一个单词,即使句子结束并且没有右括号:

     String s = "This is the work (my real job) which is great, and (also some stuff";

     ArrayList<String> words = new ArrayList<String>();
     Scanner sentence = new Scanner(s);
     boolean inParen = false;
     StringBuilder inParenWord = new StringBuilder();
     while(sentence.hasNext()) {
        String word = sentence.next();
        if(inParen) {
           inParenWord.append(" ");
           inParenWord.append(word);

           if(word.endsWith(")")) {
              words.add(inParenWord.toString());
              inParenWord = new StringBuilder();
              inParen = false;
           }
        }
        else {
           if(word.startsWith("(")) {
              inParen = true;
              inParenWord.append(word);
           }
           else {
              words.add(word);
           }
        }
     }

     if(inParenWord.length()>0) {
        words.add(inParenWord.toString());
     }


     for(String word : words) {
        System.out.println(word);
     }

会输出:

This
is
the
work
(my real job)
which
is
great,
and
(also some stuff

或者使用模式/匹配器:

     String s = "This is the work (my real job) which is great, and (also somet stuff";

     ArrayList<String> words = new ArrayList<String>();

     Pattern p = Pattern.compile(" ?([^(][^ ]+|\\([^\\)]+\\)?)");
     Matcher m = p.matcher(s);

     while(m.find()) {
        words.add(s.substring(m.start(),m.end()).trim());
     }

     for(String word : words) {
        System.out.println(word);
     }

【讨论】:

  • 嵌套括号呢?这只是我的好奇心
  • @AmirPashazadeh 它不适用于嵌套括号,) 的非贪婪匹配将匹配嵌套的括号。
【解决方案2】:

我相信您需要类似的东西(尽管我不确定这个正则表达式是否 100% 正常工作)。
简单的说;匹配(word-with-no-spaces) | (\(words-and-spaces-non-greedy\))

^[[(\w)]*|[(\(.+?)\)]*]*$

【讨论】:

  • 我需要一个适用于(带空格的单词)的正则表达式。顺便说一句,这个正则表达式不适用于我上面给出的示例:(
猜你喜欢
  • 1970-01-01
  • 2015-12-26
  • 2014-04-20
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多