NonameSL
NonameSL

Reputation: 27

Replacing all sets of words in string with other sets of words

I am trying to flip every hebrew set of characters inside a string. Lets say I have this string(Instead of hebrew letters, I will be using symbols):

§♀♠♪ this is my message♣♠♦►♣

(You can probably tell which character is in which language). And I want this character set - §♀♠♪ to be replaced with ♪♠♀§.

But, I want message♣♠♦►♣ to be replaced with message♣►♦♠♣, so only the english word inside this will stay unreversed.

How can I do that? (Yes, I know I cant use these symbols in a regular string but this is an example.)

Upvotes: 0

Views: 353

Answers (2)

Pshemo
Pshemo

Reputation: 124235

This solution is based on example provided by OP (the one with ♣♠♦►♣) but wasn't tested on real data.

  • You should be able to find sequence of two or more Hebrew characters via \p{InHebrew}{2,}.

  • When you will find them you can use String#reverse method to reverse them.

  • Last thing is to use appendReplacement and appentTail from Matcher to create new string with updated matched parts.

Here is example which should do what you want

String yourString = ...;//place for your string
Pattern p = Pattern.compile("\\p{InHebrew}{2,}");
Matcher m = p.matcher(yourString);

StringBuffer sb = new StringBuffer();

while(m.find()){
    m.appendReplacement(sb, new StringBuilder(m.group()).reverse().toString());
}
m.appendTail(sb);

String reversedSpecial = sb.toString();
System.out.println(reversedSpecial);

Upvotes: 1

WIZARDELF
WIZARDELF

Reputation: 3885

assume there's an output buffer keeping the final string: when encountering a hebrew character, read it onto a stack, until an english character is found, and then pop out all letter(s) in the stack to the output buffer; english letters are moved to the output buffer directly.

Upvotes: 0

Related Questions