Removing single-letter words using java pattern matching

I want to exclude all single-letter words from a string in Java using pattern matching. I am encoded as follows:

String str = " P@ "; //remove single char words and extra white spaces inputStr = inputStr.replaceAll("\\b[\\w']{1}\\b", "").replaceAll("\\s+", " ").trim(); 

I expect output as P @ since input is not a single letter word. But I get the output as @ because it eliminates P. Thus, basically it only considers alphabetic characters to match the pattern. While I want to match the length of the input string.

Please, help.

+4
source share
4 answers

Try using this:

  String data = "asd df R# $R $$ $ 435 4ee 4"; String replaceAll = data.replaceAll("(\\s.\\s)|(\\s.$)", " "); System.out.println(replaceAll); 

Output: asd df R# $R $$ 435 4ee

+2
source

Use this

 str = str.replaceAll("(^.$|\\s.\\s|^.\\s|\\s.$)", "").replaceAll("\\s+", " ").trim(); 

The problem with your solution was that you used \b , which was expecting a character at the end and beginning of a word so that it does not work in your case.

/b

Matches in position between the word character (everything that matches the \ w character) and the non-word character (everything that matches [^ \ w] or \ W), as well as at the beginning and / or end of the line if the first and / or last characters in a string are word characters.

REFER FOR REGULAR EXPRESSION

0
source

Try this regex:

 \s([^\s]{1})\s 

You should catch single characters without spaces, marked with a space on both sides. If you need to accept characters without spaces, such as ',' and '.' as separators you will need to add them.

0
source

Test case:

asd df R # $ R $$ $ 435 4ee 4 hey buddy this is a test i @wanted

 "[!-~]?\\b[Az]\\b[!-~]?" "[!-~]?\\b[\\w]\\b[!-~]?" 

output for above code:

asd df $$ $ 435 4ee 4 hey buddy this is the test required
asd df $$ $ 435 4ee hey buddy this test wants

note that in the second there are no four. The second regular expression gets rid of numbers that donโ€™t know if one number is counted or not

0
source

All Articles