I need a way to remove only the first space found in a string and then put the string in an array. For example
hello there. Hey.
I want that to be split like [hello][there. Hey]. I tried with
String [] s = str.split(" ")
by that will naturally remove all the spaces and create several strings. i just need 2. Can you please tell me how to do that ? Ether by regular expression or another way.
String [] s = str.split (" ", 2); should do the trick, documentation here.
You may also want to consider using \s+ as the regex - it may split the string more intelligently.
Using a regular expression for this isn't necessarily your best option.
Find the first space using position() (whatever the java method is), and then use substring() from the beginning of the string to that position, and again from that position to the end of the string.
Related
I have 2 nested HashMaps as a String which I am trying to parse.
My String is as follows :
"20:[cost:431.14, Count:19, Tax:86.228"
Therefore I need to Split by ":[" in order to get my key, 20, For some reason I'm not able to do this.
I have tried :
myString.split(":[") and myString.split("\\:[") but neither seem to work.
Can anyone detect what I have wrong here?
Thanks in Advance
You have to escape the character [ , but not the character : like below:
String str = "20:[cost:431.14, Count:19, Tax:86.228";
String[] spl = str.split(":\\[");
String.split use regex.
Splits this string around matches of the given regular expression.
You need to escape [ since this is a "reserved" character in regular expresionn, not :
myString.split(":\\[")
Not that you could/should set a limit if you only want the first cell
myString.split(":\\[", 2);
This will return an array of 2 cell, so after the first occurence, it doesn't need to read the rest of the String. (This is not really necessary but good to know).
Use Pattern.quote to automatically escape your string
String string = "20:[cost:431.14, Count:19, Tax:86.228";
String[] split = string.split(Pattern.quote(":["));
Another solution :
Therefore I need to Split by ":[" in order to get my key, 20. For
some reason I'm not able to do this.
In this case you can use replaceAll with some regex to get this input so you can use :
String str = "20:[cost:431.14, :[Count:19, Tax:86.228";
String result = str.replaceAll("(.*?):\\[.*", "$1");// output 20
regex demo
If the key is just an integer you can use (\d+):\[ check regex demo
be noted '[' character is special character in regular expression so you have to make an escape character like \\ str.split(":\\["); and remember the string is immutable so if do you want to use it twice you have to reassign it with split like this String[] spl =str.split(":\\[");
Another solution if you just need the key "20" in your String is to substring it to get the part before the delimiter.
String key = myString.substring(0, myString.indexOf(":["));
I have a String
a = "stringWithBraces()"
I want to create the following string
"stringWithBraces(text)"
How do I achieve this using regex?
I tried this :
a.replaceAll("\\(.+?\\)", "text");
But get this :
stringWithBraces()
You can use lookaheads and do something like this:
(?<=\().*?(?=\))
Live Demo
Thus doing this:
String a = "stringWithBraces()";
a = a.replaceAll("(?<=\\().*?(?=\\))", Matcher.quoteReplacement("text"));
System.out.println(a);
Outputs:
stringWithBraces(text)
Note that in relation to replaceAll() then the replacement string has some special character. So you should most likely use Matcher.quoteReplacement() in order to escape those and be safe.
You can use this :
a = a.replaceAll("\\((.*?)\\)", "(text)");
You have to replace every thing between parenthesis with (text)
+ requires at least one char, the ? added here means the shortest match, so "...(.)...(.)..." would not continue to find ".)...(.".
a.replaceAll("\\(.*?\\)", "(text)");
You might have intended replaceFirst; though I think not.
You might also let the dot . match new line chars, for mult-line matches,
using the DOT_ALL option (?s):
a.replaceAll("(?s)\\(.*?\\)", "(text)");
I have a String such as
somet3x70rnumb3r5.3.1*#:ch4r5*
I need to wrap everything that isn't *, star character, with a Pattern Quote \Q...\E and replace the * with .*. It should give this:
\Qsomet3x70rnumb3r5.3.1\E.*\Q#:ch4r5\E.*
I can do this with string traversal, splitting on * (or any character I specify), and building a string step by step, but I'd like to do use regexes and Pattern class utilities if possible.
Another example with specified character ? which would be replaced by .:
123?4?
should give
\Q123\E.\Q4\E.
I was thinking of using groups, but I need groups around every zone because each has to be either wrapped or replaced by another character.
My goal is to create a Pattern String from a given String but only consider the areas matching the specified character and ignoring the rest (even if it contains regex patterns).
Something like this?
String s = "abc*efg?123";
s = s.replaceAll("([^\\*\\?]+)", "\\\\Q$1\\\\E");
s = s.replaceAll("\\*", ".*");
s = s.replaceAll("\\?", ".");
Results in \Qabc\E.*\Qefg\E.\Q123\E
It'll be simpler if you don't worry about building a one-liner. A one-liner is probably possible, but it will be a pain. Instead, I suggest you do something like this:
str = str.replaceAll("(?<!^)\\*(?!$)", "\\E.*\\Q")
.replaceAll("(?<!^)\\?(?!$)", "\\E.\\Q");
str = "\\Q" + str + "\\E";
Simpler to write, and much easier to understand.
How do I split string using String.split() without having trailing/leading spaces or empty values?
Let's say I have string such as " ol-ga#assf-rrt.ru ; sdf.an#dfgdfg.com; sdfsdf#fdfd.erff, privet#vvv.fff ".
I used to split it by calling String.split("[;, ]+") but drawback is that you get empty array elements that you need to ignore in extra loop.
I also tried String.split("\\s*[;,]+\\s*") which doesn't give empty elements but leaves leading space in first email and trailing space in last email so that resulting array looks like because there are no commas or semicolons next to those emails:
[0] = {java.lang.String#97}" ol-ga#assf-rrt.ru"
[1] = {java.lang.String#98}"sdf.an#dfgdfg.com"
[2] = {java.lang.String#99}"sdfsdf#fdfd.erff"
[3] = {java.lang.String#100}"privet#vvv.fff "
Is it possible to get array of "clean" emails using only regex and Split (without using extra call to String.trim()) ?
Thanks!
String input = " ol-ga#assf-rrt.ru ; sdf.an#dfgdfg.com; sdfsdf#fdfd.erff, privet#vvv.fff ";
input = input.replace(" ", "");
String[] emailList = input.split("[;,]+");
I'm assuming that you're pretty sure your input string contains nothing but email addresses and just need to trim/reformat.
Like this:
String.split("\\s*(;|,|\\s+)\\s*");
But it gives an empty string in the beginning (no way to get rid of it using only split).
Thus only something like this can help:
String.trim().split("\\s*(;|,)\\s*");
Just throwing it out there: if you use Guava, Splitter makes this a bit simpler than it is with regexes.
Iterable<String> splitStrings = Splitter
.onPattern("[;,]+")
.trimResults()
.split(string);
Try using String.trim() in the result of the split
First of all, as DGomez pointed out:
String.trim()
Use that in the input string, so the leading and trailing spaces are gone.
Now, use this regex for splitting the emails:
String.split("[,;]+\\s*")
I think this should do it.
How can I split string for 3 character? (I don't want to do loop for this, maybe some regular expression will be help)
I give example:
String str = "111222333444";
String[] result = str.split("help?"); // get "111", "222", "333"
Using guava-library
Iterable<String> strNums = Splitter.fixedLength(3).split("111222333444")
Readable than using regex. You can then use Ints.tryParse(...) to get Integer version if you want.
Using .split will match regular expressions in the string which, in the underlying implementation, involves traversing the entire string anyway. Writing a simple loop to just create a token from every 3 characters would probably be more efficient.
Frankly, I don't think you can do it for a string of undefined length, without a loop.
You can not use split because the arg of split is the separator, not the resulting sub-strings.
So, your separator regex would be nothing !?
Sorry, you heve write loop. BTW, the regex engine for splitis full of loops.