j2emanue
j2emanue

Reputation: 62519

Remove all alphanumeric words from a string in java

How to find a regular expression to remove all alphanumeric words from a string ?

Here is what i have tried unsuccessfully:

assume my string is: String mystring ="the food was thrill4 not2 that good 6son";

    mystring = mystring.replaceAll("[0-9A-Za-z]","");

but its not working.

The expected results should be: "the food was that good"

Upvotes: 3

Views: 1412

Answers (2)

Gurwinder Singh
Gurwinder Singh

Reputation: 39467

Try this:

\w*\d+\w*\s*

Demo

Details:

  • \w* - starting with 0 or more word chars
  • \d+ - one or more digit
  • \w* - ends with 0 or more word chars
  • \s* - match zero or more spaces after the word

Upvotes: 2

Barmar
Barmar

Reputation: 780798

Your code is operating at the character level, not on words. Use \b to match word boundaries, and then match what's between them.

mystring.replaceAll("\\b([a-zA-Z]*[0-9]+[a-zA-Z]*)\\b", "");

Upvotes: 1

Related Questions