Java check and parse out string containing character sequence - java

I need to dynamically check for presence of char sequence "(Self)" in a string and parse it out.
So if my string say myString is
"ABCDEF (Self)"
it should return myString as
"ABCDEF"
What is the best way of doing it? Can it be done in a single step?

You may use the replace function as follows:
myString = myString.replace(" (Self)","");
Here, read more about things to note with String.replace or the function definition itself. Note that it is overloaded with a char variant, so you can do two kinds of things with a similar function call.

You may use the replaceAll method from the String class as follows:
myString = myString.replaceAll(Pattern.quote("(Self)"), ""));

Try following:
String test="ABCDEF (Self)";
test=test.replaceAll("\\(Self\\)", "");
System.out.println(test.trim());
Output :
ABCDEF
The dig is to use Regular Expressions for more on it visit this link.
And the code won't have a problem if there is no Self in string.

Just check out the String class' public methods.
String modifyString(String str) {
if(str.contains("(Self)")) {
str = str.replace("(Self)", "");
str = str.trim();
}
return str;
}

From the question, I understand that from source string ABCDEF (Self) also the space between F and ( should be removed.
I would recommend to use regEx if you are comfortable with it, else:
String OrigString = "ABCDEF (Self)";
String newString= OrigString.replaceAll("\\(Self\\)", "").trim();
System.out.println("New String : --" +newString+"--");
The Regular Expression for your case would be:
\s*\(Self\)\s*
Tested Java Code using regular expression would be:
String newRegExpString = OrigString.replaceAll("\\s*\\(Self\\)\\s*", "");
System.out.println("New String : -" +newRegExpString+"--");
Output:
New String : --ABCDEF--
New String : -ABCDEF--

Related

How to fix ReplaceAll function in java code

i am trying to replace all occurrences of the first character in a string with another using the replace all function. However, no change occurs when i run the function. I tried to target the first character of the original string and then carry the out the replacement but no luck. Below is a snippet of my code.
public static String charChangeAt(String str, String str2) {
//str = x.xy
//str2 = d.w
String res = str.replaceAll(Character.toString(str.charAt(0)), str2);
return res ;
}
Your code replaces all characters that match the first character. If your string is abcda and you run your function, it will replace all occurences of a with whatever you put. Including the last one.
To achieve your goal you should probably not use replaceAll.
You could use StringBuilder.
StringBuilder builder = new StringBuilder(str);
myName.setCharAt(0, str2.charAt(0));
In case you want to replace all occurrences of the first character in a string with another, you can use replace instead of replaceAll. Below is the code snippet.
String str = "x.xy";
String str2 = "d.w";
String res = str.replace(Character.toString(str.charAt(0)), str2);
return res; // will output d.w.d.wy
Your function works fine but you probably are using it the wrong way.
For these strings:
String str = "abaca";
String str2 = "x";
if you do:
charChangeAt(str, str2);
this will not affect str.
You must assign the value returned by your function to str:
str = charChangeAt(str, str2);
This will change the value of str to:
"xbxcx"

Getting rid of half a String in Android

Need help with getting rid of half of a string in android studio. The string is:
final String strOrigin = String.valueOf(origin).trim();
The value that is returned is;
"Point{type=Point, bbox=null, coordinates=[27.993726079654873,-26.14686805145815]}"
I want to be left with only the numbers of that, in the String. I have tried;
strOrigin.replace("Point{type=Point, bbox=null, coordinates=", "");
But it isn't working. Any help would be appreciated.
In Java strings are immutable. You must assign the result to a new string:
String strResult = strOrigin.replace("Point{type=Point, bbox=null, coordinates=", "");
Make your life simpler by just getting the coordinates:
final String strOigin = origin.coordinates().stream()
.map(String::valueOf)
.collect(Collectors.joining(",","{","}"));
Or, if you're stuck on java 7:
final String strOigin = String.format(
"{%s,%s}",
String.valueOf(origin.latitude()),
String.valueOf(origin.longitude())
);
Maybe you forgot that replace() returns the result and you must assign it to a string:
String strOrigin = "Point{type=Point, bbox=null, coordinates=[27.993726079654873,-26.14686805145815]}";
String str = strOrigin
.replace("Point{type=Point, bbox=null, coordinates=", "")
.replace("}","");
System.out.println(str);
will print:
[27.993726079654873,-26.14686805145815]
This should do the trick
String s="blabla coordinates=[27.993726079654873,-26.14686805145815] ";
String requiredString = s.substring(s.indexOf("[") + 1, s.indexOf("]"));
will print:
27.993726079654873,-26.14686805145815
Than you can cast it to double or latlong format
Have a look at regular expressions, they allow you to define more flexible search patterns. In your example you only find the coordinates if the rest of the string matches the pattern exactly, but if you happen to get some other value of bbox, or even extra space it will not work. This will always match everything between a pair of square brackets:
String c = origin.replaceAll(".+?(\\[.+?\\]).+?", "$1");
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Java replaceAll - regex variable not replaced

I have one variable representing the regex, when run replaceAll, none of string is replaced. Please help to take a look.
String s = "Issue 3 for 5 describe the title";
String regex = "Issue\\s\\d+\\sfor\\s\\d+";
System.out.println(s.replaceAll(regex, "test"));
replaceAll returns the modified String, but it does not modify the original String, as String in Java is immutable.
You need to:
String resultString = s.replaceAll(regex, "test")
System.out.println(resultString);
Java String is immutable.
If you want to change string s use this:
s = s.replaceAll(regex, "test"));
This could be caused by the fact that in your code you have to double escape your regexp, but in the xml you don't:
String regex = "Issue\\s\\d+\\sfor\\s\\d+";
is equivalent to the parsed
<regex>Issue\s\d+\sfor\s\d+</regex>

Split a String In Java against the split rule?

I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);

How to replace \ with . in java String

I want to replace \ with . in String java.
Example src\main\java\com\myapp\AppJobExecutionListener
Here I want to get like src.main.java.com.myapp.AppJobExecutionListener
I tried str.replaceAll("\\","[.]") and str.replaceAll("\\","[.]") but it is not working.
I am still getting original string src\main\java\com\myapp\AppJobExecutionListener
String is immutable in Java, so whatever methods you invoke on the String object are not reflected on it unless you reassign it.
String s = "ABC";
s.replaceAll("B","D");
System.out.println(s); //still prints "ABC"
s = s.replaceAll("B","D");
System.out.println(s); //prints "ADC"
Currently you're using replaceAll, which takes regular expression patterns. That makes life much more complicated than it needs to be. Unless you're trying to use regular expressions, just use String.replace instead.
In fact, as you're only replacing one character with another, you can just use character literals:
String replaced = original.replace('\\', '.');
The \ is doubled as it's the escape character in Java character literals - but as the above doesn't use regular expressions, the period has no special meaning.
Assign it back to string str variable, .String#replaceAll doesn't changes the string itself, it returns a new String.
str = str.replaceAll("\\\\",".")
Can you try this:
String original = "Some text with \\ and rest of the text";
String replaced = original.replace("\\",".");
System.out.println(replaced);
'\' character is doubled in a string like '\\'. So '\\' character should be used to replace it with '.' character and also using replace instead of replaceAll would be enough to make it. Here is a sample;
public static void main(String[] args) {
String myString = "src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
System.out.println("Before Replaced: " + myString);
myString = myString.replace("\\", ".");
System.out.println("After Replaced: " + myString);
}
This will give you:
Before Replaced: src\main\java\com\vxl\appanalytix\AppJobExecutionListener
After Replaced: src.main.java.com.vxl.appanalytix.AppJobExecutionListener
With String replaceAll(String regex, String replacement):
str = str.replaceAll("\\\\", ".");
With String replace(char oldChar, char newChar):
str = str.replace('\\', '.');
With String replace(CharSequence target, CharSequence replacement)
str = str.replace("\\", ".");
String replaced = original.replace('\', '.');
try this its works well
Use replace instead of replaceall
String my_str="src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
String my_new_str = my_str.replace("\\", ".");
System.out.println(my_new_str);
DEMO AT IDEONE.COM
replaceAll takes a regex as the first parameter.
To replace the \ you need to double escape. You need an additional \ to escape the first . And as it is a regex input you need to escape those again. As other answers have said string is immutable so you will need to assign the result
String newStr = str.replaceAll("\\\\", ".");
The second parameter is not regex so you can just put . in there but note you need four slashes to replace one backslash if using replaceAll
i tried this:
String s="src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
s = s.replace("\\", ".");
System.out.println("s: "+ s);
output: src.main.java.com.vxl.appanalytix.AppJobExecutionListener
Just change the line to
str = str.replaceAll("\\",".");
Edit : I didnt try it, because the problem here is not whether its a correct regex,but the problem here is that he is not assigning the str to new str value. Anyways regex corrected now.

Categories

Resources