If i have these three different string:
String line = "A man walking down the road";
String word = "the road";
String sub = "the street";
and basically want to return this:
"A man walking down the street"
Can this be done with contains (to check if the string 'word' is included in the string 'text', and then replace to replace the text ? Because i've been trying to work this out for a while now, and i haven't got anywhere.
This can be done like this:
String line = "A man walking down the road";
String word = "the road";
String sub = "the street";
System.out.println(line.replace(word,sub));
Related
String str = "My name is {0} {1} {2}."
String st = MessageFormat.format(str, "Peter", "", "Maxwell");
So basically, what this print is :
My name is Peter (whitespace) Maxwell.
Let's say, If my string has got multiple placeholders and if I pass a blank
argument, in that case the output adds up whitespace for that blank argument.
So, in our previous case, the output should be like:
My name is Peter Maxwell. (No extra whitespace between Peter and Maxwell)
Scenario 2:
String st = MessageFormat.format(str, "Peter", "Branson", "");
Actual:
**My name is Peter Branson (whitespace).**
Expected:
**My name is Peter Branson.**
What I want to achieve is, for every unsupplied placeholder argument
the whitespace should not be part of the final output.
Would appreciate the response !!
You could use a regular expression to replace multiple white space characters with a single one. Like,
String st = MessageFormat.format(str, "Peter", "", "Maxwell")
.replaceAll("\\s+", " ");
or to handle the second case as well
String st = MessageFormat.format(str, "Peter", "", "Maxwell")
.replaceAll("\\s+", " ")
.replaceAll("\\s+\\.", ".");
Which outputs (as requested)
My name is Peter Maxwell.
with no other changes
I have a string like this :
My word is "I am busy" message
Now when I assign this string to a pojo field, I get is escaped as below :
String test = "My word is \"I am busy\" message";
I have some other data in which I want something to be replaced by above string :
Let say my base string is :
String s = "There is some __data to be replaced here";
Now I when I use replaceAll :
String s1 = s.replaceAll("__data", test);
System.out.println(s1);
This returns me the output as :
There is some My word is "I am busy" message to be replaced here
Why that "\" is not appearing in after I replace. Do I need to escape it 2 times?
Also when use it like this :
String test = "My word is \\\"I am busy\\\" message";
then also it gives the same output as :
There is some My word is "I am busy" message to be replaced here
My expected output is :
There is some My word is \"I am busy\" message to be replaced here
Try this:
String test = "My word is \\\\\"I am busy\\\\\" message";
String s = "There is some __data to be replaced here";
System.out.println(s.replaceAll("__data", test));
To get the \ in your output you need to use \\\\\
From the docs:
Note that backslashes () and dollar signs ($) in the replacement
string may cause the results to be different than if it were being
treated as a literal replacement string; see Matcher.replaceAll. Use
Matcher.quoteReplacement(java.lang.String) to suppress the special
meaning of these characters, if desired.
So you can use Matcher.quoteReplacement(java.lang.String)
String test = "My word is \"I am busy\" message";
String s = "There is some __data to be replaced here";
System.out.println(s.replaceAll("__data", test), Matcher.quoteReplacement(test));
You need to use four backslashes to print a single backslash.
String test = "My word is \\\\\"I am busy\\\\\" message";
String s = "There is some __data to be replaced here";
System.out.println(s.replaceAll("__data", test));
OR
String test = "My word is \"I am busy\" message";
String s = "There is some __data to be replaced here";
System.out.println(s.replaceAll("__data", test.replace("\"", "\\\\\"")));
Output:
There is some My word is \"I am busy\" message to be replaced here
I want to separate string i.e combination of Subject Name with Subject Code into two parts in java.
The originalString can be ANYTHING like "ABC (01dfv)" , "BCD (sdfsd) etc...
The subject code always written in () and subject name will always prefix the bracket.
Example :
String originalString = "Computer Science (06cs43)"
String subjectName="Computer Science"
String subjectCode="06cs43"
I am using string.replaceAll but not able to find out the regular expression for extracting or replacing the subject code.
The size of the subject code is not fixed.
No need to use regex here. You can just do this
String orS="Computer Science (06cs43)";
String subjectName=orS.subString(0,orS.indexOf('(')-1);
String subjectCode=orS.subString(orS.indexOf('('),orS.length()-2)
Just try with followinf regex:
"^([^(]+) \\(([^)]+)\\)$"
Or better:
String originalString = "Computer Science (06cs43)";
String[] parts = originalString.split("\\(");
String subjectName = parts[0].trim();
String subjectCode = null;
if (parts.length > 1) {
subjectCode = parts[1].replaceAll("\\)$", "");
}
With this string "ADACADABRA". how to extract "CADA" From string "ADACADABRA" in java.
and also how to extract the id between "/" and "?" from the link below.
http://www.youtube-nocookie.com/embed/zaaU9lJ34c5?rel=0
output should be: zaaU9lJ34c5
but should use "/" and "?" in the process.
and also how to extract the id between "/" and "?" from the link below.
http://www.youtube-nocookie.com/embed/zaaU9lJ34c5?rel=0
output should be: zaaU9lJ34c5
Should be :
String url = "http://www.youtube-nocookie.com/embed/zaaU9lJ34c5?rel=0";
String str = url.substring(url.lastIndexOf("/") + 1, url.indexOf("?"));
String s = "ADACADABRA";
String s2 = s.substring(3,7);
Here 3 specifies the beginning index, and 7 specifies the stopping point.
The string returned contains all the characters from the beginning index, up to, but not including, the ending index.
I'm not entirely sure what you mean by extract, so I've provided the code to remove it from the String, I'm not certain if this is what you want.
public static void main (String args[]){
String string = "ADACADABRA";
string = string.replace("CADA", "");
System.out.println(string);
}
This is untested but something like this may help for the youtube part:
String youtubeUrl = "http://www.youtube-nocookie.com/embed/zaaU9lJ34c5?rel=0";
String[] urlParts = youtubeUrl.split("/");
String videoId = urlParts[urlParts.length - 1];
videoId = videoId.substring(0, videoId.indexOf("?"));
Extracting CADA from the string makes no sense. You will need to specify how you have determined that CADA is the string to extract.
E.g. is it because it is the middle 4 characters? Is it because you are stripping off 3 characters each side? Are you just looking for the String "CADA"? Is it characters 3,7 of the String? Is it the first 4 of the last 7 characters of a String? Is it because it contains 2 vowels and 2 consanants? I could go on..
String regex = "CADA";
Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
Matcher m = p.matcher(originalText);
while (m.find()) {
String outputThis = m.group(1);
}
Use this tool http://www.regexplanet.com/advanced/java/index.html
Probably, you don't take in account the fact of java.lang.String immutability. That's why you need to assign the result of substringing to a new variable.
This is a part of a string
test="some text" test2="othertext"
It contains a lot more of similar text with same formating. Each "statment" is separate by empty space
How to search by name(test, test2) and replace its values(stuff between "")?
in java
I dont know if its clear enough but i dont know how else to explain it
I want to search for "test" and replace its content with something else
replace
test="some text" test2="othertext"
with something else
Edit:
This is a content of a file
test="some text" test2="othertext"
I read content of that file in a string
Now i want to replace some text with something else
some text is not static it can be anything
You can use the replace() method of String, which comes in 3 types and 4 variants:
revStr.replace(oldChar, newChar)
revStr.replace(target, replacement)
revStr.replaceAll(regex, replacement)
revStr.replaceFirst(regex, replacement)
Eg:
String myString = "Here is the home of the home of the Stars";
myString = myString.replace("home","heaven");
///////////////////// Edited Part //////////////////////////////////////
String s = "The quick brown fox test =\"jumped over\" the \"lazy\" dog";
String lastStr = new String();
String t = new String();
Pattern pat = Pattern.compile("test\\s*=\\s*\".*\"");
Matcher mat = pat.matcher(s);
while (mat.find()) {
// arL.add(mat.group());
lastStr = mat.group();
}
Pattern pat1 = Pattern.compile("\".*\"");
Matcher mat1 = pat1.matcher(lastStr);
while (mat1.find()) {
t = mat.replaceAll("test=" + "\"Hello\"");
}
System.out.println(t);
So you want to replace every instance of "test" with something else?
Let's say the string name is myString:
myString = myString.replace("test","something else");
Is this what you are looking to do?
I think you are asking that you fetch data from file in the form of string,
lets suppose, your string is,
String s = "My name="sahil" and my company="microsoft", also i live in
country="india"".
Now you want to replace "sahil" with "mahajan" and "microsoft" with "google".
I have tried experimenting with the string methods to implement this functionality, but didnt find a relavent result. But i could provide you with some methods. You could use regionMatches, indexOf("name=""). But these functions will help you in finding where sahil(suppose) is located. but the replcae function here is difficult to work, because it replaces character sequence, for which you should know the exact character sequence.
Now you might try experimenting with the string methods. It could help.
I haven't tested this, but it should work:
String mFileContents;
private void replaceValue(String name, String newValue) {
int nameIndex = mFileContents.indexOf(name);
int equalSignIndex = mFileContents.indexOf("=", nameIndex);
int oldValueIndex = equalSignIndex + 2;
int oldValueLength = mFileContents.indexOf("\"", oldValueIndex);
String oldValue = mFileContents.substring(oldValueIndex, oldValueLength);
String firstHalf = mFileContents.substring(0, oldValueIndex -1);
String secondHalf = mFileContents.substring(oldValueIndex);
secondHalf.replaceFirst(oldValue, newValue);
mFileContents = firstHalf + secondHalf;
}
String a = "some text";
a = a.replace("text", "inserted value");
System.out.print(a);
Try this