2012-06-29 30 views
4

我試圖找出是否有任何方法在Java中,我會實現以下。從一段字符串中選擇一個單詞?

我想通過一種方法如下面

"(hi|hello) my name is (Bob|Robert). Today is a (good|great|wonderful) day." 

我想的方法選擇的由分離的括號內詞語之一的參數「|」並用隨機選擇的單詞之一返回完整的字符串。 Java是否有任何方法,或者我是否必須使用循環中的字符檢查來自己編碼?

+0

正則表達式是您的目的的最佳選擇... –

回答

6

您可以通過正則表達式解析它。

正則表達式應該是\(\w+(\|\w+)*\);在替換中,你只需將參數分割爲'|'並返回隨機單詞。

喜歡的東西

import java.util.regex.*; 

public final class Replacer { 

    //aText: "(hi|hello) my name is (Bob|Robert). Today is a (good|great|wonderful) day." 
    //returns: "hello my name is Bob. Today is a wonderful day." 
    public static String getEditedText(String aText){ 
    StringBuffer result = new StringBuffer(); 
    Matcher matcher = fINITIAL_A.matcher(aText); 
    while (matcher.find()) { 
     matcher.appendReplacement(result, getReplacement(matcher)); 
    } 
    matcher.appendTail(result); 
    return result.toString(); 
    } 

    private static final Pattern fINITIAL_A = Pattern.compile(
    "\\\((\\\w+(\\\|\w+)*)\\\)", 
    Pattern.CASE_INSENSITIVE 
); 

    //aMatcher.group(1): "hi|hello" 
    //words: ["hi", "hello"] 
    //returns: "hello" 
    private static String getReplacement(Matcher aMatcher){ 
    var words = aMatcher.group(1).split('|'); 
    var index = randomNumber(0, words.length); 
    return words[index]; 
    } 

} 

(注意,這個代碼寫只是爲了說明一個想法,可能不會編譯)

+0

是的正則表達式將是最好的選擇 – RTA

1

根據我的知識,java沒有任何方法可以直接執行。

我必須寫代碼,或regexe

0

我不認爲Java有什麼事情是你想要做什麼直。就個人而言,而不是做基於正則表達式或字符的事情,我會做的方法是這樣的:

String madLib(Set<String> greetings, Set<String> names, Set<String> dispositions) 
{ 
    // pick randomly from each of the sets and insert into your background string 
} 
0

有這個沒有直接的支持。理想情況下,您不應嘗試低級解決方案。

你應該搜索'隨機句生成器'。你寫的方式

`(Hi|Hello)` 

等被稱爲語法。你必須爲語法寫一個解析器。再次有許多解決方案用於編寫解析器。有標準的方法來指定語法。尋找BNF。

解析器和生成器問題已經解決了很多時間,並且問題的有趣部分將寫入語法。

+0

解析器這一個將是一個大問題,我認爲 – RTA

5

可能有幫助,

傳遞三個字符串( 「喜|你好」),(鮑勃|羅伯特)和(好|大|精彩)作爲參數傳遞給方法。

內部方法將字符串拆分爲數組 ,firststringarray[]=thatstring.split("|");將其用於其他兩個。

和使用this使用隨機字符串選擇。

+0

仍然我認爲正則表達式將是最好的和直接的解決方案 – RTA

0

Java不爲此提供任何現成的方法。您可以使用Penartur描述的Regex,也可以創建自己的java方法來分割字符串並存儲隨機單詞。如果遵循第二種方法,StringTokenizer類可以幫助您。

相關問題