文パーサーが必要です。パーサーが白い文字に基づいて完全な文を分割する場所。そして、括弧内の完全な内容を 1 つの単語 (解析されたもの) として扱います。
入力文:-
「これが素晴らしい仕事(私の本業)です。」
必要な出力:-
This
is
the
work
(my real job)
which
is
great.
この正規表現を使用して、そのような文から単語を解析する良い方法があるかどうかはわかりません。関係なく、文を反復処理する必要がある場合があります。あなたのためにそれをするつもりはないと思い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);
}
これに似たものが必要だと思います (ただし、この正規表現が 100% 正常に機能するかどうかはわかりません)。
シンプルに言った。マッチ(word-with-no-spaces) | (\(words-and-spaces-non-greedy\))
^[[(\w)]*|[(\(.+?)\)]*]*$