PRATHAP S
PRATHAP S

Reputation: 775

Replacing some series of words with other words

I have a String as Follows

String sentence = "I tried to speak @td Spanish @ty, and my @yd friend tried to @yi speak English @yy.";

I want to replace @td, @ty, @yi.. etc words by empty space(''). @xx words are dynamic, keeps changing in different scenarios.

How can it be done?

Thanks

Upvotes: 2

Views: 107

Answers (3)

garyh
garyh

Reputation: 2852

The regex you need is /\s@.+?\b/g. Then replace the matches with empty string.

This matches any words starting with @

See http://regexr.com/38v6d

Upvotes: 0

Savv
Savv

Reputation: 431

Try this:

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String sentence = "I tried to speak @td Spanish @ty, and my @yd friend tried to @yi speak English @yy.";

        sentence = sentence.replaceAll(" \\@[a-z]+", "");

        System.out.println(sentence);
    }
}

Upvotes: 2

shree.pat18
shree.pat18

Reputation: 21757

Try this:

sentence.replaceAll("@[A-za-z]+","");

The regex @[A-za-z]+ will look for all words composed of letters only, starting with the @ symbol, and having at least 1 letter.

Alternatively, if it is guaranteed that the words are at least 2 letters long, you can use the regex @[A-za-z]{2,}, and if they will be exactly 2 letters long, then @[A-za-z]{2}.

Upvotes: 1

Related Questions