This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
I am trying to parse data from the [] in a String in java
String text = "some text [Karan] some text";
I want to the computer to read Karan present inside the brackets
I have tried String.split() method but it packs it into an array which I don't want.
Is there any way to do this. Thank you
You can use regex like this:
String text = "some text [Karan] some [test2] text [test3] [test4] 22[test5]";
Pattern pattern = Pattern.compile("(?<=\\[).*?(?=\\])");
//or use this regex,it works well too
//Pattern pattern = Pattern.compile("(?<=\\[)[^\\[\\]]*(?=\\])");
Matcher matcher = pattern.matcher(text);
while(matcher.find()){
System.out.println(matcher.group());
}
and the result is Karan,test2,test3,test4,test5.
Regex is useful for processing text.This improved version of regular is using "Positive and Negative Lookbehind".Thanks for Matthieu's suggestions.
You might want to use the String.substring method in combination with String.indexOf.
Here is a short description of how you would extract text between brackets [] using these two methods:
Get the index of the first bracket [ character using String.indexOf method. (let's call this value start)
Get the index of the second bracket ] character using String.indexOf method (let's call this value end)
Call .substring on the string you are extracting information from with
text.substring(start+1, end)
Note how the first index start+1 is inclusive and end is exclusive.
Looks like this then:
String text = "some text [Karen] some text";
text = text.substring(text.indexOf("[") + 1, text.indexOf("]"));
System.out.println(text);
Related
This question already has answers here:
How to extract numbers from a string and get an array of ints?
(13 answers)
Closed 1 year ago.
For example, if I have these strings, is there any way I can get 123 of all these strings, or 777 or 888?
https://www.example.com/any/123/ and
https://www.example.com/any/777/123/ and
https://www.example.com/any/777/123/888
What I mean is how to match the first or second or the third last number in the string.
You can use capture groups to solve this as
val strList = listOf("https://www.example.com/any/777/123/888", "https://www.example.com/any/123/", "https://www.example.com/any/777/123/")
val intList = mutableListOf<Int>()
val regex = Regex("/?(\\d+)")
strList.forEach { str ->
regex.findAll(str).forEach {
intList.add(it.groupValues[1].toInt())
}
}
Assuming the digits all follow a slash and nothing intervenes,
(?<=/)\d+(?=/\d+){0}$ parses the last number
(?<=/)\d+(?=/\d+){1}$ parses the second to last number
(?<=/)\d+(?=/\d+){2}$ parses the third to last,
etc.
With Java, You can make use of the Pattern and Matcher class from the java.util.regex package.
e.g for your case above, you want to match integers - use \d Predefined character class to match digits.
String str = "https://www.example.com/any/777/123/";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
for(; matcher.find(); System.out.println(matcher.group()));
In the above you loop through the String finding matches, and printing each subsequent found match.
This question already has answers here:
Java - String replace exact word
(6 answers)
Closed 3 years ago.
String str = "hdfCity1kdCity12fsd".
I want to replace only City1 with Goa without replacing City1 sequence in City1X in above String.
I tried using replace function.
str = str.replace("City1", "Goa")
but the result is
str = "hdfGoakdGoa2fsd"
how to do this selective replace? to get this desired result
str = "hdfGoakdCity12fsd";//solution: str.replaceAll("(?<!\\d)City1(?!\\d)", "Goa");
sorry for making my case not clear
Thanks #TiiJ7
In your case you could use replaceFirst(). This will only replace the first occurence of your matched String:
String str = "City1 is beautiful than City12";
str = str.replaceFirst("City1", "Goa");
System.out.println(str);
Will output:
Goa is beautiful than City12
Other than that you could use a more sophisticated regex to match your exact case, see for example this answer.
You can use replaceFirst() or replaceAll() method, but if you want to replace in the middle, you can find the occurrence you are looking for (one example here: Occurrences of substring in a string)
Use the index returned to make 2 substrings: the first part remain unchanged and, in the second part, the first occurrence must be replaced (replaceFirst())
Last: join the two substrings.
you can use the method replaceFirst(regex, replacement) :
String str = "City1 is beautiful than City12";
System.out.println(str.replaceFirst("City1", "Goa")); // Goa is beautiful than City12
If it's just about the first part, you could also use the substring method.
Example:
String str = "City1 is beautiful than City12";
str = "Goa" + str.substring(5);
If you're sure that City1 will not any characters around except whitespace you can use:
String str = "City1 is beautiful than than City12";
str = str.replace("City1 ", "Goa ");
System.out.println(str);
same as yours but additional space at the end of the replacing and new string
This question already has answers here:
Java Regex Capturing Groups
(4 answers)
Closed 6 years ago.
I need to get the string between by_ and _on.
So far I have this, but don't understand how to truncate the actual "string delimiters":
by_(.*)_on
Sample input:
Files_by_wesasegeaazedude_on_January_26.jpg
Current Match:
by_wesasegeaazedude_on
Needed Match:
wesasegeaazedude
Your expression is good*. All you need to do is extracting the content of the first capturing group:
Pattern regex = Pattern.compile("by_(.*)_on");
String str = "Files_by_wesasegeaazedude_on_January_26.jpg";
Matcher m = regex.matcher(str);
if (m.find()) {
String res = m.group(1);
}
Demo.
* Well, almost good. If you expect inputs with multiple file names on the same line, you may want to consider using reluctant qualifier, i.e. by_(.*?)_on
I would do this without regular expressions.
int start = str.indexOf("by_");
int end = str.indexOf("_on", start + 1); // or lastIndexOf("_on"), for greedy match.
assert start > 0 && end > start;
String part = str.substring(start + 3, end);
You can simply use positive lookarounds:
String regex = "(?<=by_).*(?=_on)";
What this regex does is:
match anything: .*
that is preceded by by_: (?<=by_)
and followed by _on: (?=_on)
As i haven't much worked on regex, can someone help me out in getting the answer for below thing:
(1)I want to remove a text say Element
(2)It may of may not followed by delimiter say pipe(||)
I tried below thing, but it is not working in the way i want:
String str = "String:abc||Element:abc||Value:abc"; // Sample text 1
String str1 = "String:abc||Element:abc"; // Sample text 2
System.out.println(str.replaceFirst("Element.*\\||", ""));
System.out.println(str1.replaceFirst("Element.*\\||", ""));
Required output in above cases:
String:abc||Value:abc //for the first case
String:abc //for the second case
Assuming that you can decide to give another value to the original pattern which is Element in this case, you can use Pattern.quote to escape it as below:
String str = "String:abc||Element:abc||Value:abc"; // Sample text 1
String str1 = "String:abc||Element:abc"; // Sample text 2
String originalPattern = "Element";
String pattern = String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern));
System.out.println(str.replaceFirst(pattern, ""));
System.out.println(str1.replaceFirst(pattern, ""));
Your patter is then generic and its value is String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern))
Output:
String:abc||Value:abc
String:abc
You put the escape wrong. It should be:
Element(.*?\|\||.*$)
Put the escape on each pipe, and use ? for non greedy Regex so you only replace just enough string, not everything.
String text = "String:abc||Element:abc||Value:abc";
text = text.replaceAll("\\belement\\b", "");
you might need to use replace all this will replace all element from your string here i am using '\b' word boundary in java regular expression in between the words
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Simple way to determine if string is only characters, or to check if string contains any numbers in Java
I want to find if a given String has any alphabetic or numeric characters. How would I do this using java?
Thanks
String s = "%$a*";
Pattern p = Pattern.compile("[a-zA-Z0-9]");
Matcher m = p.matcher(s);
if (m.find())
System.out.println("The string \"" + s + "\" contains alphanumerical characters.");
Take a look at this:
http://www.regular-expressions.info/java.html
There are two convenience methods in the Character class that would help you
isLetter(...)
isDigit(...)
All that's required is transforming a String to a character array, and then stepping through the array.