Reputation: 193
I'm new in using regex in java and now having problems getting my regular expression working.
I want to keep minimum 3 characters in a string, if it only 2 characters, i want to delete it.
here's my string :
It might be more sensible for real users if I also included a lower limit on the number of letters.
The output i want :
might more sensible for real users also includedlower limit the number letters.
So, i did some googling but still doesnt work. so basically here's the complete code (1-5 is the regex i've tried):
String input = "It might be more sensible for real users if I also included a lower limit on the number of letters.";
//1. /^[a-zA-Z]{3,}$/
//2. /^[a-zA-Z]{3,30}$/
//3. \\b[a-zA-Z]{4,30}\\b
//4. ^\\W*(?:\\w+\\b\\W*){3,30}$
//5. [+]?(?:[a-zA-Z]\\s*){3,30}
String output = input.replaceAll("/^[a-zA-Z]{3,}$/", "");
System.out.println(output);
Upvotes: 1
Views: 1114
Reputation: 894
You can use \\w{1,3}
to get any 1-2 word characters. You then need to make sure they are not adjacent to other word characters before removing them, so you check for non-word characters (\\W
) and beginning or ending of the line (^
and $
) like so:
String output = input.replaceAll("(^|\\W)\\w{1,3}($|\\W)", " ");
Note the extra space cleans up for the potentially 2 spaces we are removing.
Upvotes: 0
Reputation: 8012
You can try this:
package com.stackoverflow.answer;
public class RegexTest {
public static void main(String[] args) {
String input = "It might be more sensible for real users if I also included a lower limit on the number of letters.";
System.out.println("BEFORE: " + input);
input = input.replaceAll("\\b[\\w']{1,2}\\b", "").replaceAll("\\s{2,}", " ");
System.out.println("AFTER: " + input);
}
}
Upvotes: 2