Parse signed number from string - java

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"

Related

How to put new string between commas in original string

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

Regex to convert this String

How can I convert this String AB23-01-0001 to AB23010001( replacing the "-" with "") and AB230001 (removing the middle part) using regex in Java, right row I'm using replace for the first case and substring and appending them into a SB for the second case. Just wanted to know how to achieve it using REGEX.
Why not use the method built into the String class?
String newString = "AB23-01-0001".replaceAll("[-]", "");
Note the use of [] - a regex string, since you are just replacing a -, you can omit them.
str = "AB23-01-0001"
happy = str.replaceAll("[^a-zA-Z0-9]", "");
from https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)
Try this:
Pattern p1 = Pattern.compile("-[^-]*-");
Matcher m1 = p1.matcher("AB23-01-0001");
System.out.println(m1.replaceAll(""));
To test it
A replacement to the patter is Pattern.compile("-[\\d\\w]+-")
You can use build-in method to remove both parts at once with RegEx:
String value = "AB23-01-0001";
value = value.replaceAll("-[\\d\\w]+-", "");

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]", ""));

Eliminating Unicode Characters and Escape Characters from String

I want to remove all Unicode Characters and Escape Characters like (\n, \t) etc. In short I want just alphanumeric string.
For example :
\u2029My Actual String\u2029
\nMy Actual String\n
I want to fetch just 'My Actual String'. Is there any way to do so, either by using a built in string method or a Regular Expression ?
Try
String stg = "\u2029My Actual String\u2029 \nMy Actual String";
Pattern pat = Pattern.compile("(?!(\\\\(u|U)\\w{4}|\\s))(\\w)+");
Matcher mat = pat.matcher(stg);
String out = "";
while(mat.find()){
out+=mat.group()+" ";
}
System.out.println(out);
The regex matches all things except unicode and escape characters. The regex pictorially represented as:
Output:
My Actual String My Actual String
Try this:
anyString = anyString.replaceAll("\\\\u\\d{4}|\\\\.", "");
to remove escaped characters. If you also want to remove all other special characters use this one:
anyString = anyString.replaceAll("\\\\u\\d{4}|\\\\.|[^a-zA-Z0-9\\s]", "");
(I guess you want to keep the whitespaces, if not remove \\s from the one above)

How to replace all matching patterns only if it does not match another pattern?

I want to replace a substring that matches a pattern, only if it does not match a different pattern. For example, in the code shown below, I want to replace all '%s' but leave ':%s' untouched.
String template1 = "Hello:%s";
String template2 = "Hello%s";
String regex = "[%s&&^[:%s]]";
String str = template1.replaceAll(regex, "");
System.out.println(str);
str = template2.replaceAll(regex, "");
System.out.println(str);
The output should be:
Hello:%s
Hello
I am missing something in my regex. Any clues? Thanks!
Use a negative lookbehind to achieve your goal:
String regex = "(?<!:)%s";
It matches %s only if there is not a : right before it.

Categories