java - select a word from a section of string? -


i'm trying find out if there methods in java me achieve following.

i want pass method parameter below

"(hi|hello) name (bob|robert). today (good|great|wonderful) day." 

i want method select 1 of words inside parenthesis separated '|' , return full string 1 of words randomly selected. java have methods or have code myself using character character checks in loops?

you can parse regexes.

the regex \(\w+(\|\w+)*\); in replacement split argument on '|' , return random word.

something like

import java.util.regex.*;  public final class replacer {    //atext: "(hi|hello) name (bob|robert). today (good|great|wonderful) day."   //returns: "hello name bob. today 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];   }  }  

(note code written illustrate idea , won't compile)


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -