I want to ask if i got one variable.
for example:
String i = "1+1+1"
how do i check the string contain digit alternate with symbol.
if you have idea how to use regex also can.
my rough idea like this:-
Pattern=[0-9\-];
if(i.matches(Pattern) {
system.out.println("true");
else
system.out.println("false);
tq.
still new here
You can use (for integers only))
^(\d+[+\/%-])*\d+$
Explanation:
^ start of the string
\d+[+\/%-] any integer followed by an operator in the character set
* any number of times
\d+ followed by an integer
$ end of the string
See Demo
If you want to do it in java then to very a character as an integer at index x use this
String s = abc.substring(x, x+1);
Scanner scan = new Scanner(s);
if (scan.hasNextInt())
{
.
}
where abc is the given string.
Check weather the first character is integer if so then start from first if not then check second (as it is alternate) then loop over the string verying if integers are present at alternate position.
Related
If a string is a = 000102.45600. I need to convert it to a = ---102.45600.
Any help in java using either regex or String formatter?
Tried the following:
a = a.replaceFirst("^0+(?!$)","-");
but i am getting only a = -102.45600 not 3 dashes.
Rules: Any leading zeros before decimal in string should be replaced by that many dashes.
000023.45677 to ----23.45677
002345.56776 to --2345.56776
00000.45678 to -----.45678
Hopefully I am clear on what my need is?
String subjectString = "000102.45600";
String resultString = subjectString.replaceAll("\\G0", "-");
System.out.println(resultString); // prints ---102.45600
\G acts like \A (the start-of-string anchor) on the first iteration of replaceAll(), but on subsequent passes it anchors the match to the spot where the previous match ended. That prevents it from matching zeroes anywhere else in the string, like after the decimal point.
See: reference SO answer.
This should do it:
String number = //assign a value here
for (int i=number.length();i>0; i--) {
if (number.substring(0,i).matches("^0+$")) {
System.out.println(number.replaceAll("0","-"));
break;
}
}
This searches for the longest substring of number which starts at index 0 and consists entirely of zeroes - starting by checking the entire String, then shortening it until it finds the longest substring of leading zeroes. Once it finds this substring, it replaces each zero with a dash and breaks out of the loop.
Why not convert the start of the string to the "." to an integer, convert it back to a string then compare the lengths. 000102 length = 6. 102 length = 3. You would have your preceding zero count.
I am writing something that will take a user's input for a phone number and tell the user if their input was valid or not based on five parameters:
input is 13 characters in length
char at index 0 is '('
char at index 4 is ')'
char at index 8 is '-'
All other characters must be one of the digits: ’0’ through ’9’ inclusive.
So far I have everything down except the 5th parameter. My code for that goes as followed
if (number.contains("[0-9]+"))
{
ints = true;
if (number.contains("[a-zA-Z]*\\d+."))
{
ints = false;
}
}
else
{
ints = false;
}
(Side note: number is my string that is the user's input, and ints is a boolean declared earlier in the code).
Here is a regular expression to do it.
Pattern p = Pattern.compile("^\\(\\d{3}+\\)\\d{3}+-\\d{4}");
System.out.println(p.matcher("(916)628-4563").matches());
System.out.println(p.matcher("( 916 ) 628-4563").matches());
output:
true
false
It can be tough to enter data like this and when receiving user input you should try to limit their options. eg. ask for each part of the phone number, and omit (,) and -.
As the op has added new requirements. First check for the required (,), and -'s.
boolean goodNumber = number.find("(")==0&&number.find(")")==4
goodNumber = goodNumber&&number.find("-")==8
goodNumber = goodNumber&&number.length()==13&&
goodNumber = goodNumber&&number.replaceAll("\\d","").length()==3;
Find the brackets, the dash and then remove all of the numbers and see if you are only left with a bracket and dash.
You can use following. If the string is correct it will print valid, otherwise it will print invalid.
public void compare(){
String inputString="(123)848-3452";
if(inputString.matches("^\\([0-9]{3}\\)[0-9]{3}-[0-9]{4}")){
System.out.println("valid");
}else{
System.out.println("invalid");
}
}
You can have a simple regex like this
Pattern pattern = Pattern.compile("\\(\\d{3}\\)\\d{3}\\-\\d{4}");
Matcher matcher = pattern.matcher("(071)234-2434");
System.out.println(matcher.matches());
I have a quite simple question here is that i have a string 0-1000
say str = "0-1000"
I successfully extract 0 and 1000 by using str.split("-")
Now, I am assigned to check the number because i am noticed that those two numbers can be a negative.
If I continue str.split("-"), then I will skip the negative sign as well.
Could anyone suggest methods for me?
Since String.split() uses regular expressions to split, you could do something like this:
String[] nos = "-1000--1".split("(?<=\\d)-";
This means you split at minus characters that follow a digit, i.e. must be an operator.
Note that the positive look-behind (?<=\d) needs to be used since you only want to match the minus character. String.split() removes all matching separators and thus something like \d- would remove digits as well.
To parse the numbers you'd then iterate over the array elements and call Integer.valueOf(element) or Integer.parseInt(element).
Note that this assumes the input string to be valid. Depending on what you want to achieve, you might first have to check the input for a match, e.g. by using -?\d--?\d to check whether the string is in format x-y where x and y can be positive or negative integers.
You can use regex like this :Works for all cases
public static void main(String[] args) {
String s = "-500--578";
String[] arr = s.split("(?<=\\d)-"); // split on "-" only if it is preceeded by a digit
for (String str : arr)
System.out.println(str);
}
O/P:
-500
-578
I want to have a regular expression in Java to match a pattern where $ does not come before the first occurrence any digit in a given string. So far what I've got is ([^$].*?)(\\d+?), but it matches the strings where $ comes a few characters before the first digit. Am I missing something?
For eg.,
dfn$jnjkdd84fjbd$bjk should be invalid ($ comes before 8), while
vsdivnsoi5$ier5girneg is valid (5 and then $).
EDIT: Minimum one digit should be present in the string.
^[^$\\d]*[\\d].*$ should do the trick.
We check that all the characters before the first digit are not "$" and not a number.
final String invalid = "dfn$jnjkdd84fjbd$bjk";
final String valid = "vsdivnsoi5$ier5girneg";
final String regexp = "^[^$\\d]*[\\d].*$";
System.out.println(invalid.matches(regexp)); // false
System.out.println(valid.matches(regexp)); // true
You could use a combination of substring() and matches() like this :
public static void main(String[] args) {
String s = "adsaa12s$21";
s = s.substring(0, s.indexOf("$")); // upto $
System.out.println(s);
System.out.println(s.matches(".*?\\d.*?")); // does my string contain digits?
}
O/P:
adsaa12s
true
s = "sfs$21";
O/P:
sfs
false
I'd use:
^[^\\$]*\\d+[^\\$]*\\$
(?![^0-9]+\$.*)(?=.*?\d.*?\$.*)(^.*$)
use this.This uses a lookahead to ensure a digit before $.
See demo.
http://regex101.com/r/yX3eB5/8
My friend helped me find a really short regex -
^[^$0-9]+[0-9].*
I need a regex which will satisfy both conditions.
It should give me true only when a String contains both A-Z and 0-9.
Here's what I've tried:
if PNo[0].matches("^[A-Z0-9]+$")
It does not work.
I suspect that the regex below is slowed down by the look-around, but it should work regardless:
.matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$")
The regex asserts that there is an uppercase alphabetical character (?=.*[A-Z]) somewhere in the string, and asserts that there is a digit (?=.*[0-9]) somewhere in the string, and then it checks whether everything is either alphabetical character or digit.
It easier to write and read if you use two separate regular expressions:
String s = "blah-FOO-test-1-2-3";
String numRegex = ".*[0-9].*";
String alphaRegex = ".*[A-Z].*";
if (s.matches(numRegex) && s.matches(alphaRegex)) {
System.out.println("Valid: " + input);
}
Better yet, write a method:
public boolean isValid(String s) {
String n = ".*[0-9].*";
String a = ".*[A-Z].*";
return s.matches(n) && s.matches(a);
}
A letter may be either before or after the digit, so this expression should work:
(([A-Z].*[0-9])|([0-9].*[A-Z]))
Here is a code example that uses this expression:
Pattern p = Pattern.compile("(([A-Z].*[0-9])|([0-9].*[A-Z]))");
Matcher m = p.matcher("AXD123");
boolean b = m.find();
System.out.println(b);
Here is the regex for you
Basics:
Match in the current line of string: .
Match 0 or any amount of any characters: *
Match anything in the current line: .*
Match any character in the set (range) of characters: [start-end]
Match one of the regex from a group: (regex1|regex2|regex3)
Note that the start and end comes from ASCII order and the start must be before end. For example you can do [0-Z], but not [Z-0]. Here is the ASCII chart for your reference
Check the string against regex
Simply call yourString.matches(theRegexAsString)
Check if string contains letters:
Check if there is a letter: yourString.matches(".*[a-zA-Z].*")
Check if there is a lower cased letter: yourString.matches(".*[a-z].*")
Check if there is a upper cased letter: yourString.matches(".*[A-Z].*")
Check if string contains numbers:
yourString.matches(".*[0-9].*")
Check if string contains both number and letter:
The simplest way is to match twice with letters and numbers
yourString.matches(".*[a-zA-Z].*") && yourString.matches(".*[0-9].*")
If you prefer to match everything all together, the regex will be something like: Match a string which at someplace has a character and then there is a number afterwards in any position, or the other way around. So your regex will be:
yourString.matches(".*([a-zA-Z].*[0-9]|[0-9].*[a-zA-Z]).*")
Extra regex for your reference:
Check if the string stars with letter
yourString.matches("[a-zA-Z].*")
Check if the string ends with number
yourString.matches(".*[0-9]")
This should solve your problem:
^([A-Z]+[0-9][A-Z0-9]*)|([0-9]+[A-Z][A-Z0-9]*)$
But it's unreadable. I would suggest to first check input with "^[A-Z0-9]+$", then check with "[A-Z]" to ensure it contains at least one letter then check with "[0-9]" to ensure it contains at least one digit. This way you can add new restrictions easily and code will remain readable.
What about ([A-Z].*[0-9]+)|([0-9].*[A-Z]+) ?
Try using (([A-Z]+[0-9])|([0-9]+[A-Z])) .It should solve.
use this method:
private boolean isValid(String str)
{
String Regex_combination_of_letters_and_numbers = "^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$";
String Regex_just_letters = "^(?=.*[a-zA-Z])[a-zA-Z]+$";
String Regex_just_numbers = "^(?=.*[0-9])[0-9]+$";
String Regex_just_specialcharachters = "^(?=.*[##$%^&+=])[##$%^&+=]+$";
String Regex_combination_of_letters_and_specialcharachters = "^(?=.*[a-zA-Z])(?=.*[##$%^&+=])[a-zA-Z##$%^&+=]+$";
String Regex_combination_of_numbers_and_specialcharachters = "^(?=.*[0-9])(?=.*[##$%^&+=])[0-9##$%^&+=]+$";
String Regex_combination_of_letters_and_numbers_and_specialcharachters = "^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[##$%^&+=])[a-zA-Z0-9##$%^&+=]+$";
if(str.matches(Regex_combination_of_letters_and_numbers))
return true;
if(str.matches(Regex_just_letters))
return true;
if(str.matches(Regex_just_numbers))
return true;
if(str.matches(Regex_just_specialcharachters))
return true;
if(str.matches(Regex_combination_of_letters_and_specialcharachters))
return true;
if(str.matches(Regex_combination_of_numbers_and_specialcharachters))
return true;
if(str.matches(Regex_combination_of_letters_and_numbers_and_specialcharachters))
return true;
return false;
}
You can delete some conditions according to your taste