Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select a word from a section of string?

Tags:

java

string

I'm trying to find out if there are any methods in Java which would me achieve the following.

I want to pass a method a parameter like below

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

I want the method to select one of the words inside the parenthesis separated by '|' and return the full string with one of the words randomly selected. Does Java have any methods for this or would I have to code this myself using character by character checks in loops?

like image 552
Arya Avatar asked Dec 16 '22 22:12

Arya


2 Answers

You can parse it by regexes.

The regex would be \(\w+(\|\w+)*\); in the replacement you just split the argument on the '|' and return the random word.

Something like

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];
  }

} 

(Note that this code is written just to illustrate an idea and probably won't compile)

like image 169
penartur Avatar answered Dec 30 '22 23:12

penartur


May be it helps,

Pass three strings("hi|hello"),(Bob|Robert) and (good|great|wonderful) as arguments to the method.

Inside method split the string into array by, firststringarray[]=thatstring.split("|"); use this for other two.

and Use this to use random string selection.

like image 27
Shalini Avatar answered Dec 30 '22 21:12

Shalini