How to use `regex` to trim a parsed String? - java

I could have used Decimal Format, but I must use regex in this case.
I have the following String myString = "0.44587628865979384"; I need to trim it to three decimal places, so that is looks like 0.445
I tried the following:
String myString = "0.44587628865979384";
String newString = myString.replaceFirst("(^0$.)(\\d{3})(\\d+)","$1$2");
// But this does not work. What is the problem in here?

It's not (^0$.). It's (\\d*.)
String newString = myString.replaceAll("(\\d*.)(\\d{3})(\\d+)", "$1$2");

Well, one suitable pattern could be "^\d\.\d{3}", though you will have to do a match to retrieve it (i.e. you're fetching what you need, not replacing what you don't need as in your example).
... but, why would you use regex for this job?
Regex is used to find common patterns in text and lets you extract/remove/list them. It is not intended to deal with string measurement
What you need is to slice the string into a subset of characters using the substring method:
myString.substring(5);
If the position of the decimal point varies:
myString.substring(myString.indexOf(".") + 4);
Remember: "Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems." (http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html)

Try this:
String newString = myString.replaceAll"(.*\\....).*", "$1");

Related

Java regex - How to get spaces and characters?

I am very confused on how Java's regular expressions work. I want to extract two strings from a pattern that looks like this:
String userstatus = "username = not ready";
Matcher matcher = Pattern.compile("(\\.*)=(\\.*)").matcher(userstatus);
System.out.println(matcher.matches());
But printing this will return false. I want to get the username, as well as the space that follows it, and the status string on the right of the equals sign and then store them both separately into two strings.
How would I do this? Thank you!
So the resulting strings should look like this:
String username = "username ";
String status = " not ready";
First, I assume that you are doing this as a learning exercise on regex, because a non-regex solution is easier to implement and to understand.
The problem with your solution is that you are escaping the dot, telling regex engine that you want to match literally a dot '.', not "any character". A simple fix to this problem is to remove \\:
(.*)=(.*)
Demo.
This would work, but it is not ideal. A better approach would be to say "match everything except =, like this:
([^=]*)=(.*)
Demo.
With \\.* you are trying to match zero or many dot characters. So the expression "(\\.*)=(\\.*)" actually expects something like ..=. or ..=. The wild card for any character is a simple .. To fix your code, you can change your regular expression to "(.*)=(.*)". This would match as many characters as it can before the = symbol and all the characters afterwards.
However, this solution is ugly and is not the best approach to do the job. The best thing to do is to use the split method if you want to extract what's on the left and the right side of the = sign.
You can use the split() method of a String.
String[] parts = userstatus.split("=");
String username = parts[0];
String status = parts[1];
- If its a question of fetching 2 String with = as the point of separation, then I think regex will be overkill for it.
- One can use split() method to handle this.
String lhs_Str = userstatus.split("=")[0]
String rhs_Str = userstatus.split("=")[1]

How do I use one regex pattern to make a String become another regex pattern in Java?

Providing a simple example can yield to solutions that I am not asking for, and alternative solutions will not work since I got much more complicated patterns to solve.
Lets say that you have a String 123.321
This String can be represented with regex as [0-9]*\\.[0-9]*
What I want to do is replace "." with "," to obtain 123,321.
Therefore, I want the regex pattern [0-9]*\\.[0-9]* to become a regex pattern [0-9]*,[0-9]*
Is it possible to indicate two regex patterns and make a String that matches the first pattern become a String that matches the second pattern?
How would I do it ?
What would be the simplest solution?
You could use \\d* to match optional digits and group the digit matches with (). Then use String.replaceAll(String, String) like
String str = "123.321";
if (str.matches("\\d*\\.\\d*")) {
str = str.replaceAll("(\\d*)\\.(\\d*)", "$1,$2");
}
System.out.println(str);
Output is (as requested)
123,321

Split String if it has number

Hi Guys its been a while since I ask another question,
I have this String which consist of a name and a number
Ex.
String myString = "give11arrow123test2356read809cell1245cable1257give222..."
Now what I am trying to do is to split it whenever there is a number attached to it
I have to split it so that I could have a result like this
give11, arrow123, test2356, read809, cell1245, cable1257, give222, ....
I could use this code but I cant find the right regex
String[] arrayString = myString.split("Regex")
Thanks for your help.
You can use a combination of lookarounds to split your string.
Lookarounds are zero-width assertions. They don't consume any characters on the string. The point of zero-width is the validation to see if a regex can or cannot be matched looking ahead or looking back from the current position, without adding them to the overall match.
String s = "give11arrow123test2356read809cell1245cable1257give222...";
String[] parts = s.split("(?<=\\d)(?=\\D)");
System.out.println(Arrays.toString(parts));
Output
[give11, arrow123, test2356, read809, cell1245, cable1257, give222, ...]
Use this regex for spliting
String regex = "(?<=\\d)(?=\\D)";
I am unfamiliar with using regex in java, but this expression matches what you need on www.rubular.com
([A-Za-z]+[0-9]+)

Getting a specific word in a string

I am new to java, i have a string
"rdl_mod_id:0123456789\n\nrdl_mod_name:Driving Test\n\nrdl_mod_type:PUBL\n\nrdl_mod_mode:Practice\n\nrdl_mod_date:2013-04-23"
What I want is to get the Driving Test word. The word is dynamically changes so what I want to happen is get the word between the rdl_mod_name: and the \n.
Try the following.. It will work in your case..
String str = "rdl_mod_id:0123456789\n\nrdl_mod_name:Driving Test\n\nrdl_mod_type:PUBL\n\nrdl_mod_mode:Practice\n\nrdl_mod_date:2013-04-23";
Pattern pattern = Pattern.compile("rdl_mod_name:(.*?)\n");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Also you can make use of regex,matcher,pattern to get your desired result..
The following links will also give you a fair idea:
Extract string between two strings in java
Java- Extract part of a string between two special characters
How to get a string between two characters?
I would look into java regular expressions (regex). The String matches method uses a regex to determine if there's a pattern in a string. For what you are doing, I would probably use 'matches(rdl_mod_.*\n)'. The '.*' is a wildcard for strings, so in this context it means anything between rdl_mod and \n. I'm not sure if the matches method can process forward slashes (they signify special text characters), so you might have to replace them with either a different character or remove them altogether.
Use java's substring() function with java indexof() function.
Try this code :
String s = "rdl_mod_id:0123456789\n\nrdl_mod_name:Driving Test\n\nrdl_mod_type:PUBL\n\nrdl_mod_mode:Practice\n\nrdl_mod_date:2013-04-23";
String sArr[] = s.split("\n\n");
String[] sArr1 = sArr[1].split(":");
System.out.println("sArr1[1] : " + sArr1[1]);
The s.split("\n\n");will split the string on basis of \n\n.
The second split i.e. sArr[1].split(":"); will split the second element in array sArr on basis of : i.e split rdl_mod_name:Driving Test into rdl_mod_name and Driving Test.
sArr1[1] is your desired result.

How to remove white spaces on either side of '=' sign?

I have the following string String string = "attr1 = 45 attr2 =\"82\"";
I am trying to remove all whitespace characters on either side of the = sign.
So that for example my output looks like:
attr1=45 attr="82"
I have tried the following:
String string = "attr1 = 45 attr2 =\"82\"";
string = string.replaceAll("\\s+", "");
I get the following output: attr1=45attr2="82"
Any suggestions would be appreciated.
You don't want to replace all spaces, but only these that are around =. Try with
string = string.replaceAll("\\s*=\\s*", "=");
Note that you cannot do this with just one regex since regexes are designed to match strings, not modify them. Regexes are often used with other tools to perform the later task. In particular, you can use String.replace() or String.replaceAll() with a very simple regex to accomplish your task.
Edit:
If you are still stumped, step back for a minute and think: How would you replace an equal sign with an asterisk, for example? Now can you modify that to do what you actually want?

Categories

Resources