6

今日は2つの正規表現タスクを実行する必要がありました。1つは適切に実行し、もう1つは失敗しました。最初のタスクは、長い長いテキストで、「F」で始まり母音で終わるすべての単語を見つけることでした。

(\bf)\w*([euioay]\b)

そしてそれは完璧に機能しました。

2つ目は、言語学の学生には難しすぎます;-) 2文字のシーケンスを少なくとも2回繰り返したすべての単語を見つける必要があります。たとえば、次のようになります。

  • tatarakはTATArak、「TA」を2回使用します。
  • brzozowskiはbrZOZOwski、「ZO」を2回使用します。
  • loremipsrecdksはloREmipsREcdks、「RE」を2回実行します。

助けてもらえますか?前もって感謝します ;-)

4

3 に答える 3

7

どれどれ:

(\w{2}) matches two letters (or digits/underscore, but let's ignore that) and captures them in group number 1. Then \1 matches whatever was matched by that group. So

\b\w*(\w{2})\w*\1

is what you're looking for (you don't need {2,} because if three letters are repeated, two letters are also repeated. Not checking for more than two makes the regex much more efficient. You can stop matching after the \1 backreference has succeeded).

于 2013-03-24T15:10:29.313 に答える
2

This pattern ought to do the trick

\b\w*?(\w{2})\w*?\1\w*?\b
  • \b is a word boundry
  • \w*? some number of letters (lazily)
  • (w{2}) exactly two letters, match and capture
  • \w*? same as above
  • \1 the content of our two letter capture group
  • \w*? same as above
  • \b another word boundry

A quick test in java:

public static void main(String[] args) {
   final Pattern pattern = Pattern.compile("\\b\\w*?(\\w{2})\\w*?\\1\\w*?\\b");
   final String string = "tatarak brzozowski loremipsrecdks a word that does not match";
   final Matcher matcher = pattern.matcher(string);
   while(matcher.find()) {
       System.out.println("Found group " + matcher.group(1) + " in word " + matcher.group());
   }
}

Output

Found group ta in word tatarak
Found group zo in word brzozowski
Found group re in word loremipsrecdks
于 2013-03-24T15:15:07.110 に答える
0

それを試してください:\b\w*?(\w{2})\w*?\1\w*\b

于 2013-03-24T15:09:09.860 に答える