Java正则表达式使用一种模式而不是两种模式

Java正则表达式使用一种模式而不是两种模式,java,regex,Java,Regex,我有一个包含行的文本文件,其中一些行的格式如下: 3个标签 如果几句话后,最后换行 我需要抓住这些行中的单词,一个接一个(用文本中每个单词的索引) 我曾考虑过使用2个正则表达式模式和2个循环的解决方案(添加了下面的代码),但我想知道是否有更好的解决方案只使用一个正则表达式模式 以下是文本中的行示例: Hello I am studying regex! This is a line in the text. Do

我有一个包含行的文本文件,其中一些行的格式如下:

  • 3个标签
  • 如果几句话后,最后换行
  • 我需要抓住这些行中的单词,一个接一个(用文本中每个单词的索引)
我曾考虑过使用2个正则表达式模式和2个循环的解决方案(添加了下面的代码),但我想知道是否有更好的解决方案只使用一个正则表达式模式

以下是文本中的行示例:

            Hello I am studying regex!
            This is a line in the text.
                Don't need to add this line
        nor this line.
            But this line should be included.
Map wordsMap=newhashmap();
模式p=Pattern.compile(\\t{3}(.*\\n”);
匹配器m=p.Matcher(文本);
模式p2=模式.compile((\S+);
匹配器m2=p.Matcher(“);
while(m.find()){
m2.复位(m组(1));
while(m2.find()){
单词map.add(m2.group(1),m.start(1)+m2.start(1));
}
}
您可以使用

(?:\G(?!^)\h+|^\t{3})(\S+)
请参阅。使用
pattern.MULTILINE
标志编译模式

获取组1数据

详细信息

  • (?:\G(?!^)\h+| ^\t{3})
    -上一个匹配的结尾,但不是在一行的开头,后跟1+水平空白字符,或者在一行的开头有三个制表符
  • (\S+)
    -组1:任何1+非空白字符
:

输出:

Match: 'Hello', Start: 3
Match: 'I', Start: 9
Match: 'am', Start: 11
Match: 'studying', Start: 14
Match: 'regex!', Start: 23
Match: 'This', Start: 33
Match: 'is', Start: 38
Match: 'a', Start: 41
Match: 'line', Start: 43
Match: 'in', Start: 48
Match: 'the', Start: 51
Match: 'text.', Start: 55
Match: 'But', Start: 113
Match: 'this', Start: 117
Match: 'line', Start: 122
Match: 'should', Start: 127
Match: 'be', Start: 134
Match: 'included.', Start: 137

不使用正则表达式的解决方案如何?0.检查包括条件1.修剪,2.按空格分割,3.排除空/仅空格的条目。嘿@Flidor,谢谢你的快速回复。我需要在这里使用正则表达式来进行此练习,我还需要原始文本中每个单词的索引。你应该补充,使用正则表达式是问题的强制性要求。
Match: 'Hello', Start: 3
Match: 'I', Start: 9
Match: 'am', Start: 11
Match: 'studying', Start: 14
Match: 'regex!', Start: 23
Match: 'This', Start: 33
Match: 'is', Start: 38
Match: 'a', Start: 41
Match: 'line', Start: 43
Match: 'in', Start: 48
Match: 'the', Start: 51
Match: 'text.', Start: 55
Match: 'But', Start: 113
Match: 'this', Start: 117
Match: 'line', Start: 122
Match: 'should', Start: 127
Match: 'be', Start: 134
Match: 'included.', Start: 137