regex for '(number)' - java

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

Related

Java regex to replace numeric values with quotes numeric values

Can someone please help with regex for replacing all integers and doubles with in a given String with single quotes :
Key1=a,Key2=2,Key3=999.6,Key4=8888,Key5=true
with this :
Key1=a,Key2='2',Key3='999.6',Key4='8888',Key5=true
I would like to use regex group capturing rules to replace all numeric string startng after = and replace with ''.
Use a look arounds each end:
String quoted = str.replaceAll("(?<==)\\d+(\\.\\d+)?(?=,|$)", "'$0'");
The entire match, which is group 0, is the number to be replaced by quotes around group 0.
The match starts with a look behind for an equals and ends with a look ahead for a comma or end of input.
You may try a regex replace all approach here:
String input = "Key1=a,Key2=2,Key3=999.6,Key4=8888,Key5=true";
String output = input.replaceAll("([^,]+)=(\\d+(?:\\.\\d+)?)", "$1='$2'");
System.out.println(output); // Key1=a,Key2='2',Key3='999.6',Key4='8888',Key5=true
Here is an explanation of the regex pattern used:
([^,]+) match and capture the key in $1
= match =
(\\d+(?:\\.\\d+)?) match and capture an integer or float number in $2
Then, we replace with $1='$2', quoting the number value.

Regex for string has condition before and after string

I want to create regex match with string has before is " " or "." and use it in replaceAll in Java.
Example:
LLS.LLS kLLS LLS
I use regex \bLLS\b.
The result I want this is LLS.
But if I want to find string "/LLS" the regex is failed.
Example: \b/LLS\b
Find in string: BBA /LLS CCA
Can you help me to find a regex?
Thanks
You could use a positive lookahead and lookbehind to assert what is on the left and rigt is either a space or a dot in a characters class.:
(?<=[ .])/?LLS(?=[ .])
In Java:
String regex = "(?<=[ .])/?LLS(?=[ .])";
Regex demo
You need to remove the first \b, you don't need to set a word boundary at the beginning
\/LLS\b
You can also make the / optional with ? to match both LLS or /LLS like so
\/?LLS\b
Here is an example https://regexr.com/48p5e

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

Trying to remove up to 2 digits following a match

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.

Problem replacing words using [^a-zA-Z] regex

Just could not get this one and googling did not help much either..
First something that I know: Given a string and a regex, how to replace all the occurrences of strings that matches this regular expression by a replacement string ? Use the replaceAll() method in the String class.
Now something that I am unable to do. The regex I have in my code now is [^a-zA-Z] and I know for sure that this regex is definitely going to have a range. Only some more characters might be added to the list. What I need as output in the code below is Worksheet+blah but what I get using replaceAll() is Worksheet++++blah
String homeworkTitle = "Worksheet%#5_blah";
String unwantedCharactersRegex = "[^a-zA-Z]";
String replacementString = "+";
homeworkTitle = homeworkTitle.replaceAll(unwantedCharactersRegex,replacementString);
System.out.println(homeworkTitle);
What is the way to achieve the output that I wish for? Are there any Java methods that I am missing here?
[^a-zA-Z]+
Will do it nicely.
You just need a greedy quantifier in order to match as many non-alphabetical characters you can, and replace the all match by one '+' (a - by default - greedy quantifier)
Note: [^a-zA-Z]+? would make the '+' quantifier lazy, and would have give you the same result than [^a-zA-Z], since it would only have matched only one non-alphabetical character at a time.
String unwantedCharactersRegex = "[^a-zA-Z]"
This matches a single non-letter. So each single non-letter is replaced by a +. You need to say "one or more", so try
String unwantedCharactersRegex = "[^a-zA-Z]+"

Categories