3

I have a string, for ex:

There exists a word *random*.

random will be a random word.
How can I use a regular expression to replace every character of random with * and have this result:

There exists a word ********.

So the * replaces every character, in this case 6 characters.
Notice that I am after to replace only the word random, not the surroundings *. So far I have:

str.replaceAll("(\\*)[^.]*(\\*)", "\\*");

But it replaces *random* with *, instead of the desired ******** (total of 8).
Any help, really appreciated...

6
  • You always want to replace word after "There exists a word"? Commented Feb 4, 2013 at 6:03
  • you want to do masking of a word between **. Am i right? Commented Feb 4, 2013 at 6:04
  • @Achintya Jha, Even the whole sentence may be different, so basically I want to replace the word wrapped in *. Commented Feb 4, 2013 at 6:06
  • @Real, I don't know what masking means. Should I search for it? Commented Feb 4, 2013 at 6:06
  • @MikeSpy.. Can you have multiple words like that? or just 1? Commented Feb 4, 2013 at 6:11

4 Answers 4

5

If you have just a single word like that: -

As far as current example is concerned, if you are having just a single word like that, then you can save yourself from regex, by using some String class methods: -

String str = "There exists a word *random*.";

int index1 = str.indexOf("*");
int index2 = str.indexOf("*", index1 + 1);

int length = index2 - index1 - 1;   // Get length of `random`

StringBuilder builder = new StringBuilder();

// Append part till start of "random"
builder.append(str.substring(0, index1 + 1));

// Append * of length "random".length()
for (int i = 0; i < length; i++) {
    builder.append("*");
}

// Append part after "random"
builder.append(str.substring(index2));

str = builder.toString();

If you can have multiple words like that: -

For that, here's a regex solution (This is where it starts getting a little complex): -

String str = "There exists a word *random*.";
str = str.replaceAll("(?<! ).(?!([^*]*[*][^*]*[*])*[^*]*$)", "*");
System.out.println(str);

The above pattern replaces all the characters that is not followed by string containing even numbers of * till the end, with a *.

Whichever is appropriate for you, you can use.

I'll add an explanation of the above regex: -

(?<! )       // Not preceded by a space - To avoid replacing first `*`
.            // Match any character
(?!          // Not Followed by (Following pattern matches any string containing even number of stars. Hence negative look-ahead
    [^*]*    // 0 or more Non-Star character
    [*]      // A single `star`
    [^*]*    // 0 or more Non-star character
    [*]      // A single `star`
)*           // 0 or more repetition of the previous pattern.
[^*]*$       // 0 or more non-star character till the end.     

Now the above pattern will match only those words, which are inside a pair of stars. Provided you don't have any unbalanced stars.

Sign up to request clarification or add additional context in comments.

10 Comments

I agree with Rohit.. Regex is used for patterns but what you are searching for is a definite thing.
Wow! That was amazing! I am trying for almost 2 hours to find a regex, with no luck at all! And you Robit Jain, came up with the regex in 5 minutes!
@Rohit Jain: Great answer +1 for you.
@MikeSpy.. haha :) Well, one day you will also make regex like that in 5 minutes. It's just a matter of experience, and nothing else. :)
Thank you very much for your complete answer and the explanation provided. I believe this is a very good reference, as I didn't find anything online.
|
2

You can extract the word between * and do a replaceAll characters with * on it.

import java.util.regex.*;

String txt = "There exists a word *random*.";
// extract the word
Matcher m = Pattern.compile("[*](.*?)[*]").matcher(txt);
if (m.find()) {
    // group(0): *random*
    // group(1): random
    System.out.println("->> " + m.group(0));
    txt = txt.replace(m.group(0), m.group(1).replaceAll(".", "*"));
}
System.out.println("-> " + txt);

You can see it on ideone: http://ideone.com/VZ7uMT

Comments

0

try

    String s = "There exists a word *random*.";
    s = s.replaceAll("\\*.+\\*", s.replaceAll(".*(\\*.+\\*).*", "$1").replaceAll(".", "*"));
    System.out.println(s);

output

There exists a word ********.

Comments

0
public static void main(String[] args) {
    String str = "There exists a word *random*.";
    Pattern p = Pattern.compile("(\\*)[^.]*(\\*)");

    java.util.regex.Matcher m = p.matcher(str);
    String s = "";
    if (m.find())
        s = m.group();

    int index = str.indexOf(s);
    String copy = str;
    str = str.substring(0, index);

    for (int i = index; i < index + s.length(); i++) {
        str = str + "*";
    }
    str = str + copy.substring(index + s.length(), copy.length());

    System.out.println(str);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.