Guys I just started learning Regular Expression in java. I am trying to construct a regular expression for a number. It is ok for integers if I use "\d+".
But if there is any decimal number, it is obvious that the above RE won't work.
So I constructed a RE that is "\d+\.\d+" . It is ok for decimal numbers but
NOT FOR INTEGERS.
So I want to make a RE for BOTH INTEGERS and DECIMALS. Any idea is appreciated.
Make the part after the decimal point optional.
"\d+(?:\.\d+)?"
The leading ?: after the initial parenthesis is just to avoid creating a matching group.
You can try to use this regex:
/^\d*\.?\d*$/
The Javadoc for java.lang.Double#valueOf(String) gives a detailed but well-documented regular expression for how it parses numbers. You may find it instructive to read that and work out which parts are relevant to your problem.
Related
I'm not sure if this is possible or not:
Writing a program to convert an infix notation to postfix notation. All is working well so far but trying to implement validation is proving difficult.
I'm trying to use a regex to validate an infix notation, conforming to the following rules:
String must only start with a number or ( (program does not allow negative numbers)
String must only end with number or )
String must only contain 0-9*/()-+
String must not allow following characters to appear together +*/-
I have a regex which conforms to the first 3 rules:
(^[0-9(])([0-9+()*]+)([0-9)]+$)
Is it possible to use regex to implement the last rule?
I will answer only to fourth rule as you have problem only with it.
Yes, there is a possibility, but I think regex is not appropriate tool to check that...
This pattern ^(?(?=.*\+)(?!.*[\*\/-])).+$ will match any string that contain + and not contain other characters: /,*,-. For one character is already lengthy and hard to read. See demo.
It uses conditional expression (?...) to check if lookahead checking for + was successfull, if it is, then negative lookahead assures that you won't have any of \*- characters.
For all characters, the regex will become very big and hard to maintain.
That's why I don't recommend it for this task.
I agree with Michał Turczyn that regex is not the task for this, but not with the reason. It is easy to implement your restrictions. However, your restrictions also allow expressions like (0+3, 2(*4), ((((1, and other things you likely don't want - so regex validation is kind of pointless. If you were writing this with a regex engine with some significant power like PCRE (Perl, PHP) or Onigmo (Ruby), you can fake a parser in regex; but in Java, regex is quite restricted in what it can do. It is enough for the requirements in the question, though:
^[0-9(](?:(?![+*/-][+*/-])[0-9+*/()-])*[0-9)]$
starts with digit or paren
any number of repetitions of any allowed character, such that that character and the next character aren't both operators
ends with digit or thesis.
I am trying to find a regex for the following user generated possibilities:
÷2%3%x#4%2$#
OR
÷2%x#4%2$#
OR
÷2%x#4$#
OR
÷2%x#
To understand the expression, it is a fraction whose numerator lies between
the ÷ and the first %, and the denominator lies from first % to the #.
But, the denominator has an exponent, which lies from the # to $.
The user can input whatever number he/she desires, but the structure stays the same. Notice that the number can also be a decimal.
The structure is as follows: ÷(a number, if its two or more digits a % will be in between the digits)x(a group that consists of a number(s), also the symbols # , $ and a %(s) which can also alternate between the digits)#
Remember, the number can be a decimal number.
I am trying to use the following regex with no success:
"[÷]-?\\d+(\\.\\d*)?[%](-?\\d+(\\.\\d*)?){0,1}[x]([#]-?\\d+(\\.\\d*)?[$]){0,1}[#]"
I think that the group (-?\d+(\.\d*)?){0,1} is complicating things up.
Also, I have not accounted for the % within this group which could occur.
any suggestions, thank you
Edit: Deleted the old post content.
According to your new testcases I improved your regex to match all cases and simplified the regex:
÷[0-9%]+?x(#[0-9%]+?\$)?# OR ÷[\d%]+?x(#[\d%]+?\$)?#
Note:
The [] mark groups of allowed characters so it has no use to have the parenthesis.
Also [÷][0-9]+[0-9[%]]+? is just the same as ÷[0-9]+[0-9%]+? the first part in your example matches any number 0-9 n-times and then you check for either (0-9 or %) for n-times (non greedy fetching). So instead you can just use the second check for the whole thing.
By wrapping the exponent in a regex-class: () we can make the whole exponent optional with ? ==> this will make your 4th test-case work.
You could also substitute 0-9 with \d (any digit) if you want.
I found a regex that works, I tested from the bottom up:
Here it is:
[÷][0-9[%][\\.]]+?[x][0-9[%][\\.][#][$]]*?[#]
This regex works for all types of cases. Even those that include decimal numbers, or not exponents.
the group [0-9[%][\.][#][$]]*? allows the regex to search for exponent, which can occur zero(that's why the * is there) or more times and the ? makes it optional. Similarly, I followed the same idea for the coefficient of x(read the post if you don't know where the coefficient lies) and the numerator. Thank you for everyone that put effort in brainstorming this problem. I have chosen to use my answer for my programming.
Here's my RegExp checker which currently doesn't work:
String pattern = "(?=.*[0-9]{3})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]{1})(?=\\S+$).{5,15}";
Here are the parameters I cannot meet yet:
5-15 characters {5,15}
exactly 3 digits (?=.*[0-9]{3})
Neither the character limit nor the digit check are working, and I can't find any examples for some reason. Where I am I going wrong? Clearly it's a placement issue, as I'm a total novice. Any help would be appreciated. The others (at least one upper/lowercase/special) I can meet, but these two simple pieces I'm still struggling with.
For three digits checking add this anywhere in your regex as you are using positive lookahead.
(?=^([^0-9]*[0-9]){3}[^0-9]*$)
For 5-15 digit check add this one:
(?=^.{5,15}$)
You can use the regex on the site https://regex101.com/ and it will give you the explanation on the right hand side.
[0-9]{3} is 3 consecutive integers. To allow three integers somewhere in the string you need to check for each integer part.
(?=^[^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*$)
.{5,15} is 5 to 15 characters but that is anywhere in the string, to have it affect the whole string that needs to be anchored. So your full expression should be:
^(?=^[^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*$)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]{1})(?=\\S+$).{5,15}$
Demo: https://regex101.com/r/UVK7ev/1
I have the user input a fraction problem in this format (4/8–3/12 or 3+2/3 or 12/16*4 or -2/3/64/96) and need to split up the two fractions into an array then I need to pull the numerator and denominator of both so I can simplify them in my other file and do whatever calculation it asks, so I need to use an array so i can call on the element that has the sign in it.
System.out.println("Enter Fraction:");
String answer = s.nextLine();
String[] numbers = answer.split(" ");
System.out.print(numbers);
Is there a way to split the array into int variables? I am lost. The solution might be simple but been at this project for 7 hours or so now.
You can split the input with a simple regular expression, like this:
Pattern p = Pattern.compile("\\d+|[+-/*]");
String inp = "2/3/64/96";
Matcher m = p.matcher(inp);
while (m.find()) {
System.out.println(m.group());
}
The heart of this solution is a regular expression:
\\d+|[+-/*]
\\d+ means "one or more digit; [+-/*] means "any of the +, -, /, or *".
Here is a demo on ideone.
Note that your program would need to be really careful about deciding if a + or a - is a unary "change sign" or a binary operation: when the sign is at the beginning or just after another operator, it's unary; otherwise, it's binary.
Eric Lippert has the best advice I've seen when dealing with these problems.
Write the problem out in english/pseudo code then start changing the pseudo code to real code.
Get Answer from user
Break Answer up to the 2 fractions/numbers and the math operator
Take the 2 different fractions and convert them to a double, float, whatever you need
Apply the math operation to the 2 numbers from the above step
Output the answer
Now just start replacing each line with how you would do that. I feel confident that you can probably figure out each step, but sometimes we get lost when thinking of the problem as a whole. If you can't figure out an individual step, post the code you have tried and we can help with a specific problem.
Your code so far just splits input into expressions. Your still need to split expressions into fractions.
When you already have String array of fractions you can split each element into 2 integers:
Split it into sub-strings with split("/")
Convert each sub-string to int with Integer.parseInt() method.
I have this pattern:
Pattern.compile("T([0-9]*)");
which works fine for positive numbers but I need it to also do negative numbers for instance "T-1T3T44" should work. Or maybe use space instead of 'T' so it should work for strings like this:"-1 2 3 2 -1 6 2". Sorry I haven't really used regular expressions before.So any suggestions? Thanks.
Pattern.compile("T(-{0,1}(?!0)\\d+)");
Please note the usage of negative look-ahead (?!0) to exclude -0 number and numbers that start with 0.
Have you thought of trying:
"T(-?[0-9]+)"
You'll notice I've also changed the "*" (zero or more) to "+" (one or more) since "" isn't technically a number :-)
Try with:
Pattern.compile("T(-?[0-9]*)");
Make the minus optional may be?
T-?([0-9]*)
Pattern.compile("T-?([0-9]*)");