Regex to convert this String - java

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

Related

How to replace a string exactly as it is?

Consider the following code:
String str = "folder1;b";
String replacement = "C:\\myfolder";
System.out.println(str.replaceAll("b", replacement));
This printsC:myfolder.
How can I replace str with the replacement string as is? (Without the slashes being removed)
I've tried Pattern.quote(replacement) but that prints \QC:\Development\E
I have no control over replacement which comes from an external source and it is not known what its contents would be.
If you aren't using regular expressions, better to use String.replace():
String str = "folder1;b";
String replacement = "C:\\myfolder";
System.out.println(str.replace("b", replacement));
String.replace() does a literal replacement, it doesn't treat the arguments as regular expressions.
I will point out that you will run into trouble if your str is folder1;bash;b as both of the bs will be replaced.
String.replaceAll uses regex. You don't need that.
Try this:
String str = "b";
String replacement = "C:\\myfolder";
System.out.println(str.replace(str,replacement);
The second parameter of String.replaceAll expect a regex. In the regex world a \ has a special operator meaning. You have to escape it once for the jvm and once for regex.
String str = "b";
String replacement = "C:\\\\\\\\myfolder";
System.out.println(str.replaceAll(str, replacement));
Will print out
C:\\myfolder
With String.replace it does take the literal string and thus you only have to escape it once for the jvm
String str = "b";
String replacement = "C:\\\\myfolder";
System.out.println(str.replace(str, replacement));
Will print
C:\\myfolder
And lastly, if you have no idea how the incoming replacement String looks like you can escape it beforehand with
String str = "b";
String replacement = "C:\\myfolder"; // might be anything
String actualReplacement = replacement.replaceAll("\\\\", "\\\\\\\\");
System.out.println(str.replace(str, actualReplacement));
Will print
C:\\myfolder
Other than that you could use one of the apache.utils to achieve it, but this one here is without any third party library.

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"

How to replace substrings that contain any integer in java?

How to replace a sub-string in java of form " :[number]: "
example:
string="Hello:6:World"
After replacement,
HelloWorld
ss="hello:909:world";
do as below:
String value = ss.replaceAll("[:]*[0-9]*[:]*","");
You can use a regex to define your desired pattern
String pattern = "(:\d+:)";
string EXAMPLE_TEST = ':12:'
System.out.println(EXAMPLE_TEST.replaceAll(pattern, "text to replace with"));
should work depending on what exactly you want to replace...
Do like this
String s = ":6:";
s = s.replaceAll(":", "");
Edit 1: After the question was changed, one should use
:\d+:
and within Java
:\\d+:
This is the answer for replacing :: as well.
This is the regexp you should use:
:\d*:
Debuggex Demo
And here is a running JavaCode snipped:
String str = "Hello :4: World";
String s = str.replaceAll(":\\d*:","");
System.out.println(s);
One problem with replaceAll is often, that the corrected String is returned. The string object from which replaceAll was called is not modified.

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

How to find and replace a substring?

For example I have such a string, in which I must find and replace multiple substrings, all of which start with #, contains 6 symbols, end with ' and should not contain ) ... what do you think would be the best way of achieving that?
Thanks!
Edit:
just one more thing I forgot, to make the replacement, I need that substring, i.e. it gets replaces by a string generated from the substring being replaced.
yourNewText=yourOldText.replaceAll("#[^)]{6}'", "");
Or programmatically:
Matcher matcher = Pattern.compile("#[^)]{6}'").matcher(yourOldText);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb,
// implement your custom logic here, matcher.group() is the found String
someReplacement(matcher.group());
}
matcher.appendTail(sb);
String yourNewString = sb. toString();
Assuming you just know the substrings are formatted like you explained above, but not exactly which 6 characters, try the following:
String result = input.replaceAll("#[^\\)]{6}'", "replacement"); //pattern to replace is #+6 characters not being ) + '
You must use replaceAll with the right regular expression:
myString.replaceAll("#[^)]{6}'", "something")
If you need to replace with an extract of the matched string, use a a match group, like this :
myString.replaceAll("#([^)]{6})'", "blah $1 blah")
the $1 in the second String matches the first parenthesed expression in the first String.
this might not be the best way to do it but...
youstring = youstring.replace("#something'", "new stringx");
youstring = youstring.replace("#something2'", "new stringy");
youstring = youstring.replace("#something3'", "new stringz");
//edited after reading comments, thanks

Categories