Java Split with 3 delimiters [ ] , - java

I want Johann as a result.
My code:
String rs = "[ Johann ,]";
String[] splitted = rs.split(","+"["+"]");

You can use following to remove all the special characters from string and filter out required output.
str = str.replaceAll("[^\\w\\s-]", "");

Try using replaceAll api of String like:
String rs = "[Johann,]";
System.out.println(rs.replaceAll("\\[|\\]|,", ""));
Output:
Johann

String.split expects a regular expression as argument. What about
String rs = "[ Johann ,]";
String[] splitted = rs.split("[,\\[\\]]");

Related

How to split a string having [] as delimiters in java

I want to remove [ ] braces from the below string-
"[maths=100, english=20]"
I have tried doing it in following ways but in both the trials it is not removing the end ] brace.
Approach 1:
String[] metrics= "[maths=100, english=20]";
String[] value = metrics[1].split("\\[");
String[] finalValue = value[1].split("\\]");
System.out.println(finalValue[0]); // this should give string as maths=100, english=20
Approach 2:
String[] metrics= "[maths=100, english=20]";
String[] value = metrics[1].split("\\[\\]");
System.out.println(finalValue[1]); // this should give string as maths=100, english=20
Can anyone guide me where i am doing it wrong?
Try this code
String metrics= "[maths=100, english=20]";
String[] split = metrics.split("\\[|]");
System.out.println(split[1]);
it prints
"maths=100, english=20"
Or you can simply replace all [ and ] character
String metrics = "[maths=100, english=20]";
metrics = metrics.replace("[", "").replace("]", "");
System.out.println(metrics);
If you simply want to trim and clean your data then you can do a simple check and substring.
String input = ...;
String cleanedInput = input.trim();
if (cleanedInput.startsWith("[") && cleanedInput.endsWith("]")) {
cleanedInput = cleanedInput.substring(1, cleanedInput.length() - 1);
System.out.println(cleanedInput);
}
If you're wanting to match and capture from a larger set of data then you can use RegEx patterns with capture groups to match and capture the data you want.
For parsing a proper document structure though you should try to use a real parser but if you truly are just trying to match and capture some simple data then RegEx will often be ok.
String input = ...;
// RegEx pattern "\[([^\[\]]*)\]" anything inside braces except other braces
Pattern pattern = Pattern.compile("\\[([^\\[\\]]*)\\]");
Matcher matcher = pattern .matcher(input);
while (matcher.find()) {
String data = matcher.group(1);
System.out.println(data);
}
You can simply replace the braces like this:
String s = "[maths=100, english=20]";
s = s.replace("[", "").replace("]", "");
System.out.println(s);

"How to replace "[" from string in java?"

I want to use the String::replaceall method in Java. I have a string which includes "[" and I want to replace that with "" but it's showing an error.
String str="already data exists = [ abc,xyz,123 ]";
String replacedStr = str.replaceAll("Already Po Exits =", "");
String replacedStr1 = replacedStr.replaceAll("\\[", "");
The following replace function will replace [ in your string.
str.replaceAll("\\[", "")
or you can use replace function to achieve the same
str.replace("[", "")
For replacing Unclosed character, you need to add escape character while replacing
String replacedStr1 = replacedStr.replaceAll("\\[", "");
You can use the replace function to do this.
String replacedStr1 = replacedStr.replace("[", "");

remove chunks of word from string

In java i have to cut word "getenforce" from string.
problem is the word I receive is sometimes cut off. For example i receive "etenforce", or "tenforc".
I could assume at least 4 letters will come in and filter it like that:
//st ---> this is string
st = st.replace("getenforce", "");
st = st.replace("gete", "");
st = st.replace("eten", "");
st = st.replace("tenf", "");
...
st = st.replace("orce", "");
is there some better, more elegant way?
You can use a for loop instead of doing this line by line.
String theWord = "getenforce";
st = st.replace(theWord, "");
//check all the sequences in loop
for(int i=0; i<theWord.length()-3;i++){
st=st.replace(theWord.subSequence(i, i+4), "");
}
I believe this will resolve your query
List<String> strings = Arrays.asList("your sentence with word gete".split(" "));
List<String> filtered = strings.stream().filter(s1 -> !s1.contains("gete")).collect(Collectors.toList());

Split the string with hyphen symbol multiple occurrence using regex /java

Getting the string value using the below xpath
String noAndDate = driver.findElement(By.xpath("//*[#id='c38']/div/table/tbody/tr[1]/td/strong")).getText();
Output of the above string = 2928554 - 2009-09-18 (BOPI 2009-38)
my expected output
2928554
2009-09-18
i tried below split, but i'm not getting my expected output
String[] words = noAndDate.split("-");
Please advice/help me
You can instead try splitting on a regex alternation which looks for a hyphen surrounded by whitespace, or pure whitespace:
String input = "2928554 - 2009-09-18 (BOPI 2009-38)";
String[] parts = input.split("(\\s+-\\s+|\\s+)");
System.out.println(parts[0]);
System.out.println(parts[1]);
Demo
Try the below code-
String str = "2928554 - 2009-09-18 (BOPI 2009-38)";
String str1 = str.split(" - | ")[0];
String str2 = str.split(" - | ")[1];
This will return str1 as 2928554 and str2 as 2009-09-18.
Hope this will help you !
Just split with regex will do.
String given = "2928554 - 2009-09-18 (BOPI 2009-38)";
String [] splitted = given.split(" - |\\s+");
String result = splitted[0] +", "+splitted[1];
System.out.println(result);
prints
2928554, 2009-09-18
Use Regex capture groups, here you can see what you want in 2 groups:
(\d+)\s*-\s*(\d+\-\d+\-\d+)
() = group
Try this:
String[] words = noAndDate.split(" ");
then
System.out.println(words[0]);
System.out.println(words[2]);

Extract last number after decimal

I am getting a piece of JSON text from a url connection and saving it to a string currently as such:
...//setting up url and connection
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = in.readLine();
When I print str, I correctly find the data {"build":{"version_component":"1.0.111"}}
Now I want to extract the 111 from str, but I am having some trouble.
I tried
String afterLastDot = inputLine.substring(inputLine.lastIndexOf(".") + 1);
but I end up with 111"}}
I need a solution that is generic so that if I have String str = {"build":{"version_component":"1.0.111111111"}}; the solution still works and extracts 111111111 (ie, I don't want to hard code extract the last three digits after the decimal point)
If you cannot use a JSON parser then you can this regex based extraction:
String lastNum = str.replaceAll("^.*\\.(\\d+).*", "$1");
RegEx Demo
^.* is greedy match that matches everything until last DOT and 1 or more digits that we put in group #1 to be used in replacement.
Find the start and the end indexes of the String you need and substring(start, end) :
// String str = "{"build":{"version_component":"1.0.111"}};" cannot compile without escaping
String str = "{\"build\":{\"version_component\":\"1.0.111\"}}";
int start = str.lastIndexOf(".")+1;
int end = str.lastIndexOf("\"");
String substring = str.substring(start,end);
just use JSON api
JSONObject obj = new JSONObject(str);
String versionComponent= obj.getJSONObject("build").getString("version_component");
Then just split and take the last element
versionComponent.split("\\.")[2];
Please, your can try the following code :
...
int index = inputLine.lastIndexOf(".")+1 ;
String afterLastDot = inputLine.substring(index, index+3);
With Regular Expressions (Rexp),
You can solve your problem like this ;
Pattern pattern = Pattern.compile("111") ;
Matcher matcher = pattern.matcher(str) ;
while(matcher.find()){
System.out.println(matcher.start()+" "+matcher.end());
System.out.println(str.substring(matcher.start(), matcher.end()));
}

Categories