How to put new string between commas in original string - java

I have this original string and I want to insert new string between two dots of original string. I did it this way, but having errors.
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String new = originalString.replace(originalString.substring(originalString.indexOf(".") + 1), stringForReplace);
it gives me: "asdASfasdlpe.NewString"
Result should be: "asdASfasdlpe.NewString.asdasfdfepw"

I would do it like so.
from the question it looks like you want to replace the first occurrence so use replaceFirst
(?<=\\.) - look behind assertion - so start with following character
(?=\\.) - look ahead assertion - so end prior to that
.*? - reluctant quantifier to limit to just characters between two periods. Use * in case you have two adjacent periods since the string could be empty.
String s = "first.oldstring.third.fourth.fifth";
String n = "second";
s = s.replaceFirst("(?<=\\.).*?(?=\\.)",n);
System.out.println(s);
prints
first.second.third.fourth.fifth

String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String a[]=originalString.split("[.]");
String newString="";
if(a.length==3) {
newString=originalString.replace(a[1], stringForReplace);
}
System.out.println(newString);
Or with ternary operator:
newString=(a.length== 3 ? originalString.replace(a[1], stringForReplace):null);
System.out.println(newString);

One shorter solution is to use regex with a lookahead and lookbehind
String replaced = originalString.replaceAll("(?<=\\.).+(?=\\.)", stringForReplace);

The problem with your code is due to using this particular piece of code:
originalString.substring(originalString.indexOf(".") + 1)
The reason is that indexof() function will only give the index on which "." was found on, and substring will only know where to start taking the substring from, but it wouldn't know where to end it.
Try this:
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String newString = originalString.replace(originalString.split("[.]", 3)[1], stringForReplace);
System.out.println(newString);
The split function in this piece of code will break the whole string by "."
and you will have the string you want to replace available to you.
originalString.split("[.]", 3)[1]

You could try the following:
public static void main(String[] args) {
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String newStr = originalString.replaceAll("(?<=\\.).*(?=\\.)", stringForReplace);
//using lookahead and lookbehind regex
String newStr2 = originalString.replaceAll("\\..*\\.", "."+stringForReplace+".");
System.out.println(newStr);
System.out.println(newStr2);
}
One option uses lookahead and lookbehinds, you could opt to not use that if it is not supported.
Output:
asdASfasdlpe.NewString.asdasfdfepw
asdASfasdlpe.NewString.asdasfdfepw

Here You go:
String new = originalString.replace(originalString.substring(originalString.indexOf(".") + 1), stringForReplace)+originalString.substring(originalString.indexOf(".",originalString.indexOf(".")+1),originalString.length());
What I have done is adding the resultant string to the new String.indexOf function takes another argument too, which is the position the search will start

Related

Parse signed number from string

I have string like:
"-------5548481818fgh7hf8ghf----fgh54f4578"
I don't want to parse using Pattern and Matcher. I have code:
string.replaceAll("regex", ""));
How to make regex to exclude all symbols except a "-" to get string like:
-554848181878544578
You can use this negative lookahead regex:
String s = "-------5548481818fgh7hf8ghf----fgh54f4578";
String r = s.replaceAll("(?!^[-+])\\D+", "");
//=> -554848181878544578
(?!^-)\D will replace each non-digit except the hyphen at start.
RegEx Demo
This will work
String Str = new String("-------5548481818fgh7hf8ghf----fgh54f4578-");
String tmp = Str.replaceAll("([-+])+|([^\\d])","$1").replaceAll("\\d[+-](\\d|$)","");
System.out.println(tmp);
Ideone Demo
Alternative: Grab the opposite, instead of replacing the negative. Seems to be arbitrary that you've picked to remove characters you don't want, instead of grabbing the characters you do want. Example in javascript:
s = "-------5548481818fgh7hf8ghf----fgh54f4578"
s = '-' + s.match(/[0-9]+/g).join('')
// "-554848181878544578"

Spilt string and match end of string with enum values

I have one string which i need to divide into two parts using regex
String string = "2pbhk";
This string i need to divide into 2p and bhk
More over second part should always be bhk or rk, as strings can be one of 1bhk, 5pbhk etc
I have tried
String pattern = ([^-])([\\D]*);
You can use the following regex "(?=bhk|rk)" with split.
str.split("(?=bhk|rk)");
This will split it if there is one of bhk or rk.
This should do the trick:
(.*)(bhk|rk)
First capture holds the "number" part, and the second bhk OR rk.
Regards
String string = "2pbhk";
String first_part, second_part = null;
if(string.contains("bhk")){
first_part = string.substring(0, string.indexOf("bhk"));
second_part = "bhk";
}
else if(string.contains("rk")){
first_part = string.substring(0, string.indexOf("rk"));
second_part = "rk";
}
Try the above once, not using regex but should work.
In case you are looking to split strings that end with rk or bhk but not necessarily at the end of the string (i.e. at the word boundaries), you need to use a regex with \\b:
String[] arr = "5ddddddpbhk".split("(?=(?:rk|bhk)\\b)");
System.out.println(Arrays.toString(arr));
If you want to allow splitting inside a longer string, remove the \\b.
If you only split individual words, use $ instead of \\b (i.e. end of string):
(?=(?:rk|bhk)$)
Here is my IDEONE demo

String replace according to position?

I have this String 11101011.I want to replace last three char '011' with 101.is there any function of String in java to do so?
Use string.replaceAll function.
string.replaceAll(".{3}$", "101");
.{3} matches exactly three characters and $ asserts that the match must be followed by an end of the line.
Example:
String name = "11101011";
String result = name.replaceAll(".{3}$", "101");
System.out.println(result);
Output:
11101101
Using String replace and regular expressions for this task seems like breaking butterflies on a wheel - just cut the last three characters off and append the new suffix (ultimately verbose solution):
final String oldString = "11101011";
final String oldSuffix = oldString.substring(5);
final String reducedOldString = oldString.substring(0, oldString.length() - oldSuffix.length());
final String newSuffix = "101";
final String newString = reducedOldString.concat(newSuffix);
System.out.println("newString = " + newString);
Use replace method of String class
String s="11101011";
System.out.println(s.replace("011","101"));
O/P:
11101101

String index out of range with replace all

How can I replace mapDir surrounded by <> to a certain string?
String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
String test = "foo: <mapDir> -bar";
println(test.replaceAll("<mapDir>", mapDir));
The above gives me a StringIndexOutOfBoundsException.
This code below for me, but I think pure java has to work as well.
static String replaceWord(String original, String find, String replacement) {
int i = original.indexOf(find);
if (i < 0) {
return original; // return original if 'find' is not in it.
}
String partBefore = original.substring(0, i);
String partAfter = original.substring(i + find.length());
return partBefore + replacement + partAfter;
}
You dont need replaceAll method as you are not using regex. Instead you could work with replace api like below:
String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replace("<mapDir>", mapDir));
replaceAll in String uses a regex, as specified in the documentation:
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.
Thus, you should escape your replacement string like this:
String mapDir = "D:\\mapping\\specialists\\ts_gpc\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replaceAll("<mapDir>", Matcher.quoteReplacement(mapDir)));
which gives the output:
foo: D:\mapping\specialists\ts_gpc\ -bar
Since replaceAll works with regex, you need to re-escape the backslashes:
String mapDir = "D:\\\\mapping\\\\specialists\\\\ts_gpc\\\\";
String test = "foo: <mapDir> -bar";
System.out.println(test.replaceAll("<mapDir>", mapDir));
Quoting this answer:
by the time the regex compiler sees the pattern you've given it, it
sees only a single backslash (since Java's lexer has turned the double
backwhack into a single one)

How to replace all numbers in java string

I have string like this String s="ram123",d="ram varma656887"
I want string like ram and ram varma so how to seperate string from combined string
I am trying using regex but it is not working
PersonName.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1))).replaceAll("[^0-9]+"));
The correct RegEx for selecting all numbers would be just [0-9], you can skip the +, since you use replaceAll.
However, your usage of replaceAll is wrong, it's defined as follows: replaceAll(String regex, String replacement). The correct code in your example would be: replaceAll("[0-9]", "").
You can use the following regex: \d for representing numbers. In the regex that you use, you have a ^ which will check for any characters other than the charset 0-9
String s="ram123";
System.out.println(s);
/* You don't need the + because you are using the replaceAll method */
s = s.replaceAll("\\d", ""); // or you can also use [0-9]
System.out.println(s);
To remove the numbers, following code will do the trick.
stringname.replaceAll("[0-9]","");
Please do as follows
String name = "ram varma656887";
name = name.replaceAll("[0-9]","");
System.out.println(name);//ram varma
alternatively you can do as
String name = "ram varma656887";
name = name.replaceAll("\\d","");
System.out.println(name);//ram varma
also something like given will work for you
String given = "ram varma656887";
String[] arr = given.split("\\d");
String data = new String();
for(String x : arr){
data = data+x;
}
System.out.println(data);//ram varma
i think you missed the second argument of replace all. You need to put a empty string as argument 2 instead of actually leaving it empty.
try
replaceAll(<your regexp>,"")
you can use Java - String replaceAll() Method.
This method replaces each substring of this string that matches the given regular expression with the given replacement.
Here is the syntax of this method:
public String replaceAll(String regex, String replacement)
Here is the detail of parameters:
regex -- the regular expression to which this string is to be matched.
replacement -- the string which would replace found expression.
Return Value:
This method returns the resulting String.
for your question use this
String s = "ram123", d = "ram varma656887";
System.out.println("s" + s.replaceAll("[0-9]", ""));
System.out.println("d" + d.replaceAll("[0-9]", ""));

Categories