Trying to remove up to 2 digits following a match - java

Say I have a few string like Foo3,5bar, Foo14,5bar and Foo23,42bar
I want to remove the second number, following the comma, as well as the comma, using Java Regex.
So far, I've tried String.replaceAll("(?<=Foo\d{1,2}),\d{1,2}", ""), using (?<=Foo\d{1,2}),\d{1,2} as my regex, but it's not working.

Use String#replaceAll that has regex support:
String str = "Foo3,4HelloFoo5,3World";
str = str.replaceAll("(\\d),\\d+", "$1"); // Foo3HelloFoo5World
OR else if you want to restrict matching to max 2 digits after comma then use:
str = str.replaceAll("(\\d),\\d{1,2}", "$1"); // Foo3HelloFoo5World
Live Demo: http://ideone.com/5P1guJ

str = str.replaceFirst(",\\d+$")

what about Integer.valueOf(str.substring(string.lastIndexOf(",")+1));
is regex a necessity ?

Your regex is almost correct. You forget to escape the \ in the regex. The correct one is:
(?<=Foo\\d{1,2}),\\d{1,2}
Note the \\ instead of \.
See https://ideone.com/W7IuT1 for a demo on your strings.

Related

regex for '(number)'

I need to replace all the 's around numbers, to nothing.. for example:
'1' to 1
'100' to 100
which is the optimal way to do this? is there a regex to do this so I can use it in the replace() function of the String class?
You can use replaceAll method with regex support:
str = str.replaceAll("'(\\d+)'", "$1");
(\\d+) will match and group digits surrounded by single quotes on either side and then we use $1 in replacement which is the back-reference to captured value in regex.
If it's in a String and you want the integer why don't you just parse it.
int a = Integer.parseInt("100");

Regular expression for splitting a String while preserving whitespace

I am doing an Android project which needs to split a String into tokens while preserving whitespaces and also not to split at non-word characters like #, & etc ...
Using \b splits at any non-word character .So i need a way to split the string in the following way.
Input: (. indicates whitespace)
A.A#..A##
Desired output:
A
.
A#
..
A##
So these 5 lines are the 5 values I would like in an array or similar. That means the 4th element of the result-array contains 2 spaces.
I think this is what you want:
(?<=\S)(?=\s)|(?<=\s)(?=\S)
Debuggex Demo
Basically I'm saying "if the previous character is a non-space and the next is a space or if the previous is a space and the next is a non-space, then split".
Use StringTokenizer:
StringTokenizer st = new StringTokenizer("A.A#..A##", ".");//first argument is string you want to split, another is whitespace
while(st.hasMoreTokens())
System.out.println(st.nextToken());
output will be:
A
A#
A##
Try:
String s = "A.A#..A##";
if(s.contains("..")) | s.contains("...")) {
s.replace("..", ".");
s.replace("...", ".");
String out[] = s.split(".");
It should give you an array with Strings the way you want :)
Don't forget to replace the "." with actual spaces :)

Remove parentheses, dashes, and spaces from phone number

I have a phone number like (123) 456-7890. I am using the replaceAll method to remove () and - and spaces from the string. I tried following
String phNo= "(123) 456-7890".replaceAll("[()-\\s]").trim();
but it's not working. Any solution?
This should work:
String phNo = "(123) 456-7890".replaceAll("[()\\s-]+", "");
In your regex:
\s should be \\s
Hyphen should be first or last in character class to avoid escaping or use it as \\-
Use quantifier + as in [()\\s-]+ to increase efficiency by minimizing # of replacements
If you want the phone number then use:
String phNo = "(123) 456-7890".replaceAll("\\D+", "");
This regex will mark all characters that are not digits, and replace them with an empty string.
The regex: \D+
Match a single character that is not a digit. \D
Between one and unlimited times, as many times as possible. +
String newStr = phoneNumber.replaceAll("[^0-9]", "");
System.out.println(newStr);
Removes All Non-Digit Characters.
Java Regex - Tutorial
IN 2022 use this! all other answers too old!!!!!!!!!!!
result = "(123) 456-7890".replace(/[^+\d]+/g, "");
The - character with brackets [] indicates a character range, e.g. [a-z]. However, the character range doesn't work here where you want a literal - to be used. Escape it.
String phNo = "(123) 456-7890".replaceAll("[()\\-\\s]", "").trim());
There are two main reasons this does not work as expected.
Inside of a character class the hyphen has special meaning. You can place a hyphen as the first or last character of the class. In some regular expression implementations, you can also place directly after a range. If you place the hyphen anywhere else you need to escape it in order to add it to your class.
String phNo = "(123) 456-7890".replaceAll("[()\\-\\s]").trim();
^^
You are not supplying a replacement value which neither answer has pointed out to you.
String phNo = "(123) 456-7890".replaceAll("[()\\-\\s]", "").trim();
^^
And finally, you can remove .trim() here as well.
String phNo = "(123) 456-7890".replaceAll("[()\\-\\s]", "");
If you are using Kotlin than
mobileNo.replace(Regex("[()\\-\\s]"), "")

Removing repeated characters in String

I am having strings like this "aaaabbbccccaaddddcfggghhhh" and i want to remove repeated characters get a string like this "abcadcfgh".
A simplistic implementation for this would be :
for(Character c:str.toCharArray()){
if(c!=prevChar){
str2.append(c);
prevChar=c;
}
}
return str2.toString();
Is it possible to have a better implementation may be using regex?
You can do this:
"aaaabbbccccaaddddcfggghhhh".replaceAll("(.)\\1+","$1");
The regex uses backreference and capturing groups.
The normal regex is (.)\1+ but you've to escape the backslash by another backslash in java.
If you want number of repeated characters:
String test = "aaaabbbccccaaddddcfggghhhh";
System.out.println(test.length() - test.replaceAll("(.)\\1+","$1").length());
Demo
With regex, you can replace (.)\1+ with the replacement string $1.
You can use Java's String.replaceAll() method to simply do this with a regular expression.
String s = "aaaabbbccccaaddddcfggghhhh";
System.out.println(s.replaceAll("(.)\\1{1,}", "$1")) //=> "abcadcfgh"
Regular expression
( group and capture to \1:
. any character except \n
) end of \1
\1{1,} what was matched by capture \1 (at least 1 times)
use this pattern /(.)(?=\1)/g and replace with nothing
Demo

how to remove only charactres in a given string in java?

I am trying to remove only [A-z|a-z] like this:
String input ="A021001208A 711100609C 01111";
String clean = input.replaceAll("\\D+^\\s+","");
System.out.println(clean.toString());
but the above code also removes the spaces; I don't want to remove space.
The expected output is:
021001208 711100609 01111
Please help me to formate the reg-ex to remove only characters.
Just replace [a-zA-Z] then:
String clean = input.replaceAll("(?i)[A-Z]+","");
(?i) is ignore case embedded flag expression.
Rather than use a positive character class, use a negated one. The regex you want is:
[^\d\s]
Which means "any character other than a digit or a whitespace".
When coded as java, it looks like:
String clean = input.replaceAll("[^\\d\\s]","");
Try this it will replace all occurence of alphabet from the given string.
String clean = input.replaceAll("[^a-zA-Z]", "");
You have to use [a-zA-Z] regular expression. So your .replaceAll() method will look like as below :
String clean = input.replaceAll("[a-zA-Z]","");

Categories