I need to replace some of the contents of a large string with different content in the same spot.
Lets say I have a string:
String str = "package blah.foo.bar;\n"
+ "import org.blah.blah;\n"
+ "import sel.this.that;\n"
+ "import sel.boo.foo;\n"
+ "...more text";
I want to insert the word gen into statements which start with import sel. So that the end result looks like: import sel.gen.this.that;
I have had success with the following method but only when I KNOW where that substring will be within the string. My issue is that I'm not sure how to make the following code dynamic:
private String modifyString(String str){
String hold = str.substring(0, str.indexOf(";"));
hold = new StringBuilder(hold).insert(13, "gen.").toString();
str = str.replace("(?m)^package.*", hold);
return str;
}
The above code correctly replaces the strings package blah.foo.bar; with package blah.gen.foo.bar;
But again this only works with replacing the beginning portion of the string. I'm looking to be able to hold all instances of a substring and then insert a substring within those substrings.
You can use a simple line like:
str = str.replaceAll("import sel\\.", "import sel.gen.");
Regex demo
IdeOne example
replace takes a literal string expression as an argument, not a regex.
This should work and is simpler than using a regex:
String result = str.replace("import sel.", "import sel.gen.");
Related
I have a string of SVG markup that contains multiples of these:
url(#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100)
and I need them to be like this:
url('#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100')
with quotes inside the parenthesis.
These will be mixed inside a long string containing lots of different markup, so needs to be very accurate.
You can use a regex like this:
\((.*?)\)
With the replacement string ('$1')
The idea is capture everything within parentheses and concatenates the '
So, you can use a code like this:
String str = "url(#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100)";
str = str.replaceAll("\\((.*?)\\)", "('$1')");
//Outuput: url('#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100')
IdeOne example
In case you want a better performance regex you can use:
str = str.replaceAll("\\(([^)]*)\\)", "('$1')");
ReplaceAll remove a part of the string and put an unrelated and invariant new stuff instead.
Because the replacement string can't be the same at both side, the only solution I imagine (with the constraint of using RegEx and ReplaceAll) is to do it in two time:
String Str = "url(#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100)";
Str = Str.replaceAll("\\(", "('"); // replace left parenthesis
Str = Str.replaceAll("\\)", "')"); // replace right parenthesis
System.out.print("Return Value: " + Str);
// Return Value: url('#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100')
You can test it here.
So, I'm trying to parse a String input in Java that contains (opening) square brackets. I have str.replace("\\[", ""), but this does absolutely nothing. I've tried replaceAll also, with more than one different regex, but the output is always unchanged. Part of me wonders if this is possibly caused by the fact that all my back-slash characters appear as yen symbols (ever since I added Japanese to my languages), but it's been that way for over a year and hasn't caused me any issues like this before.
Any idea what I might be doing wrong here?
Strings are immutable in Java. Make sure you re-assign the return value to the same String variable:
str = str.replaceAll("\\[", "");
For the normal replace method, you don't need to escape the bracket:
str = str.replace("[", "");
public String replaceAll(String regex, String replacement)
As shown in the code above, replaceAll method expects first argument as regular expression and hence you need to escape characters like "(", ")" etc (with "\") if these exists in your replacement text which is to be replaced out of the string. For example :
String oldString = "This is (stringTobeReplaced) with brackets.";
String newString = oldString.replaceAll("\\(stringTobeReplaced\\)", "");
System.out.println(newString); // will output "This is with brackets."
Another way of doing this is to use Pattern.quote("str") :
String newString = oldString.replaceAll(Pattern.quote("(stringTobeReplaced)"), "");
This will consider the string as literal to be replaced.
As always, the problem is not that "xxx doesn't work", it is that you don't know how to use it.
First things first:
a String is immutable; if you read the javadoc of .replace() and .replaceAll(), you will see that both specify that a new String instance is returned;
replace() accepts a string literal as its first argument, not a regex literal.
Which means that you probably meant to do:
str = str.replace("[", "");
If you only ever do:
str.replace("[", "");
then the new instance will be created but you ignore it...
In addition, and this is a common trap with String (the other being that .matches() is misnamed), in spite of their respective names, .replace() does replace all occurrences of its first argument with its second argument; the only difference is that .replaceAll() accepts a regex as a first argument, and a "regex aware" expression as its second argument; for more details, see the javadoc of Matcher's .replaceAll().
For it to work it has to be inside a method.
for example:
public class AnyClass {
String str = "gtrg4\r\n" + "grtgy\r\n" + "grtht\r\n" + "htrjt\r\n" + "jtyjr\r\n" + "kytht";
public String getStringModified() {
str.replaceAll("\r\n", "");
return str;
}
}
I want to replace the first space character in a string with another string listed below. The word may contain many spaces but only the first space needs to be replaced. I tried the regex below but it didn't work ...
Pattern inputSpace = Pattern.compile("^\\s", Pattern.MULTILINE);
String spaceText = "This split ";
System.out.println(inputSpace.matcher(spaceText).replaceAll(" "));
EDIT:: It is an external API that I am using and I have the constraint that I can only use "replaceAll" ..
Your code doesn't work because it doesn't account for the characters between the start of the string and the white-space.
Change your code to:
Pattern inputSpace = Pattern.compile("^([^\\s]*)\\s", Pattern.MULTILINE);
String spaceText = "This split ";
System.out.println(inputSpace.matcher(spaceText).replaceAll("$1 "));
Explanation:
[^...] is to match characters that don't match the supplied characters or character classes (\\s is a character class).
So, [^\\s]* is zero-or-more non-white-space characters. It's surrounded by () for the below.
$1 is the first thing that appears in ().
Java regex reference.
The preferred way, however, would be to use replaceFirst: (although this doesn't seem to conform to your requirements)
String spaceText = "This split ";
spaceText = spaceText.replaceFirst("\\s", " ");
You can use the String.replaceFirst() method to replace the first occurence of the pattern
System.out.println(" all test".replaceFirst("\\s", "test"));
And String.replaceFirst() internally calls Matcher.replaceFirst() so its equivalent to
Pattern inputSpace = Pattern.compile("\\s", Pattern.MULTILINE);
String spaceText = "This split ";
System.out.println(inputSpace.matcher(spaceText).replaceFirst(" "));
Do in 2 steps:
indexOf(" ") will tell you where is the index
result = str.substring(0, index) + str.substring(index+1, str.length())
The idea is this, you may need to adjust the index values properly according to API.
It should be faster than regexp, because there is 2x arraycopy and not need to text compile pattern matching and stuff.
Can use Apache StringUtils:
import org.apache.commons.lang.StringUtils;
public class substituteFirstOccurrence{
public static void main(String[] args){
String text = "Word1 Word2 Word3";
System.out.println(StringUtils.replaceOnce(text, " ", "-"));
// output: "Word1-Word2 Word3"
}
}
We can simply use yourString.replaceFirst(" ", ""); in Kotlin.
i have a link http://localhost:8080/reporting/pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName= No Technicians in Area in my struts based web application.
The variable in URL justificationName have some spaces before its vales as shown. when i get value of justificationName using request.getParameter("justificationName") it gives me that value with spaces as given in the URL. i want to remove those spaces. i tried trim() i tries str = str.replace(" ", ""); but any of them did not removed those spaces. can any one tell some other way to remove the space.
Noted one more thing that i did right click on the link and opened the link into new tab there i noticed that link looks like.
http://localhost:8080/reporting/pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName=%A0%A0%A0%A0%A0%A0%A0%A0No%20Technicians%20in%20Area
Notable point is that in the address bar it shows %A0 for white spaces and also show %20 for space as well see the link and tell the difference please if any one have idea about it.
EDIT
Here is my code
String justificationCode = "";
if (request.getParameter("justificationName") != null) {
justificationCode = request.getParameter("justificationName");
}
justificationCode = justificationCode.replace(" ", "");
Note: replace function remove the space from inside the string but not removing starting spaces.
e-g if my string is " This is string" after using replace it becomes " Thisisstring"
Thanks in advance
Strings are immutable in Java, so the method doesn't change the string you pass but returns a new one. You must use the returned value :
str = str.replace(" ", "");
Manual trim
You need to remove the spaces the string. This will remove any number of consecutive spaces.
String trimmed = str.replaceAll(" +", "");
If you want to replace all whitespace characters:
String trimmed = str.replaceAll("\\s+", "");
URL Encoding
You could also use an URLEncoder, which sounds like a more appropriate way to go:
import java.net.UrlEncoder;
String url = "http://localhost:8080/reporting/" + URLEncoder.encode("pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName= No Technicians in Area", "ISO-8859-1");
You have to assign the result of the replace(String regex, String replacement) operation to another variable. See the Javadoc for the replace(String regex, String replacement) method. It returns a brand new String object and this is because the String(s) in Java are immutable. In your case, you can simply do the following
String noSpacesString = str.replace("\\s+", "");
You can use replaceAll("\\s","") It will remove all white space.
If you are trying to remove the trailing and ending white spaces, then
s = s.trim();
Or if you want to remove all the spaces the use :
s = s.replace(" ","");
There are two ways of doing one is regular expression based or your own way of implementing the logic
replaceAll("\\s","")
or
if (text.contains(" ") || text.contains("\t") || text.contains("\r")
|| text.contains("\n"))
{
//code goes here
}
For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).
What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.
Reassign the variable to a substring:
s = s.substring(0, s.length() - 1)
Also an alternative way of solving your problem: you might also want to consider using a StringTokenizer to read the file and set the delimiters to be the characters you don't want to be part of words.
Use:
String str = "whatever";
str = str.replaceAll("[,.]", "");
replaceAll takes a regular expression. This:
[,.]
...looks for each comma and/or period.
To remove the last character do as Mark Byers said
s = s.substring(0, s.length() - 1);
Additionally, another way to remove the characters you don't want would be to use the .replace(oldCharacter, newCharacter) method.
as in:
s = s.replace(",","");
and
s = s.replace(".","");
You can't modify a String in Java. They are immutable. All you can do is create a new string that is substring of the old string, minus the last character.
In some cases a StringBuffer might help you instead.
The best method is what Mark Byers explains:
s = s.substring(0, s.length() - 1)
For example, if we want to replace \ to space " " with ReplaceAll, it doesn't work fine
String.replaceAll("\\", "");
or
String.replaceAll("\\$", ""); //if it is a path
Note that the word boundaries also depend on the Locale. I think the best way to do it using standard java.text.BreakIterator. Here is an example from the java.sun.com tutorial.
import java.text.BreakIterator;
import java.util.Locale;
public static void main(String[] args) {
String text = "\n" +
"\n" +
"For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).\n" +
"\n" +
"What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.\n" +
"\n" +
"Every help appreciated. Thanx";
BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault());
extractWords(text, wordIterator);
}
static void extractWords(String target, BreakIterator wordIterator) {
wordIterator.setText(target);
int start = wordIterator.first();
int end = wordIterator.next();
while (end != BreakIterator.DONE) {
String word = target.substring(start, end);
if (Character.isLetterOrDigit(word.charAt(0))) {
System.out.println(word);
}
start = end;
end = wordIterator.next();
}
}
Source: http://java.sun.com/docs/books/tutorial/i18n/text/word.html
You can use replaceAll() method :
String.replaceAll(",", "");
String.replaceAll("\\.", "");
String.replaceAll("\\(", "");
etc..