Reputation: 213
Assume the string is:
The/at Fulton/np-tl County/nn-tl Grand/jj-tl
How can I remove character after /
and the out put as below
The Fulton County Grand
Upvotes: 3
Views: 3333
Reputation: 5699
String text = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String newText = text.replaceAll("/.*?\\S*", "");
From Java API:
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
If you need to replace a substring or a character, use 1st 2 methods. If you need to replace a pattern or a regex, used 2nd 2 methods.
Upvotes: 2
Reputation: 30648
do as follow:
startchar : is a starting character from which you want to replace.
endchar : is a ending character up to chich character you want to replace.
" " : is because you just want to delete it so replace with white space
string.replaceAll(startchar+".*"+endchar, "")
also see greedy quantifier examples
see working example
public static void main( String[] args ) {
String startchar ="/";
String endchar="?(\\s|$)";
String input = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String clean = input.replaceAll(startchar+".*"+endchar, " ");
System.out.println( clean);
}
output
The Fulton County Grand
Upvotes: 1
Reputation: 52185
This worked for me:
String text = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String newText = text.replaceAll("/.*?(\\s|$)", " ").trim();
Yields:
The Fulton County Grand
This basically replaces any character(s) which are after a /
and are either followed by a white space or else, by the end of the string. The trim()
at the end is to cater for the extra white space added by the replaceAll
method.
Upvotes: 1
Reputation: 425073
String input = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String clean = input.replaceAll("/.*?(?= |$)", "");
Here's a test:
public static void main( String[] args ) {
String input = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String clean = input.replaceAll("/.*?(?= |$)", "");
System.out.println( clean);
}
Output:
The Fulton County Grand
Upvotes: 5
Reputation: 1500893
It looks like a simple regex-based replace could work fine here:
text = text.replaceAll("/\\S*", "");
Here the \\S*
means "0 or more non-whitespace characters". There are other options you could use too, of course.
Upvotes: 8