I want to check String contain any character or special character other than number.I wrote following code for this
String expression = "[^a-zA-z]";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(jTextFieldPurchaseOrder.getText().toString().trim());
It is working fine when i am taking value from jTextField and checking my condition. But giving error when checking String from DTO as below
list.get(0).getChalan_trans_id().toString().trim().matches("[^a-zA-z]");
Where list is arraylist of DTO.
I am not getting where am I going wrong?
Thanks
If you want to check if there is a non-digit character, you can use .*\\D.*:
if (list.get(0).getChalan_trans_id().toString().trim().matches(".*\\D.*")) {
//non-digit found, handle it
}
or, maybe easier, do it the other way around:
if (list.get(0).getChalan_trans_id().toString().trim().matches("\\d*")) {
//only digits found
}
There's probably a more efficient way than regular expressions. Regular expressions are powerful, but can be overkill for a simple task like this.
Something like this ought to work, and I would expect it to be quicker.
static boolean hasNonNumber(String s) {
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (!Character.isDigit(c)) {
return true;
}
}
return false;
}
Related
How to check whether a string is present on another string in Java, but here the conditions be like:
For Example:
String 1: Panda
String 2: "a1d22n333a4444p"
Here String 2 needs to have the letter 'p','n','d' at-least once and 'a' at-least twice. Pattern should be matches with the above conditions.
I have done with Regular Expression, but i am not getting the solution.
public static boolean isContainsAnimal(String message,String animal) {
String animalPattern=generatePattern("panda");
Pattern pattern = Pattern.compile(animalPattern);
Matcher matcher = pattern.matcher(message);
int count = 0;
while (matcher.find()) {
count++;
}
if(count>=1){
return true;
}else
{
return false;
}
}
public static String generatePattern(String animal){
String result="";
for(int i=0;i<animal.length();i++){
result+="[^"+animal.charAt(i)+"]*"+animal.charAt(i);
}
return result;
}
Suggest me a solution for this problem.
Your attempt does not take account of the different possible orderings of the characters in the animal string. In fact, for a 5 distinct character string, there are 5 factorial different orders.
It is possible to generate a regex with all of the orderings as alternates, but the result is ... horrible and inefficient.
A better idea is to work out if there are letters (like 'a') are repeated. Then generate a regex for each letter, use "match" to apply each one and AND the results.
An even better idea is to not use regexes at all. They are the wrong tool for this job.
So I currently have this code;
for (int i = 1; i <= this.max; i++) {
in = in.replace("{place" + i + "}", this.getUser(i)); // Get the place of a user.
}
Which works well, but I would like to just keep it simple (using Pattern matching)
so I used this code to check if it matches;
System.out.println(StringUtil.matches("{place5}", "\\{place\\d\\}"));
StringUtil's matches;
public static boolean matches(String string, String regex) {
if (string == null || regex == null) return false;
Pattern compiledPattern = Pattern.compile(regex);
return compiledPattern.matcher(string).matches();
}
Which returns true, then comes the next part I need help with, replacing the {place5} so I can parse the number. I could replace "{place" and "}", but what if there were multiple of those in a string ("{place5} {username}"), then I can't do that anymore, as far as I'm aware, if you know if there is a simple way to do that then please let me know, if not I can just stick with the for-loop.
then comes the next part I need help with, replacing the {place5} so I can parse the number
In order to obtain the number after {place, you can use
s = s.replaceAll(".*\\{place(\\d+)}.*", "$1");
The regex matches arbitrary number of characters before the string we are searching for, then {place, then we match and capture 1 or more digits with (\d+), and then we match the rest of the string with .*. Note that if the string has newline symbols, you should append (?s) at the beginning of the pattern. $1 in the replacement pattern "restores" the value we need.
I need to check a string whether it includes a specific arrangements of letters and numbers.
Valid arrangements are for example:
X
X-Y
A-H-K-L-J-Y
A-H-J-Y
123
12?
12*
12-17
Invalid are for example:
-X-Y
-XY
*12
?12
I have written this method in java to solve this problem (but i donĀ“t have some experiences with regular expressions):
public boolean checkPatternMatching(String sourceToScan, String searchPattern) {
boolean patternFounded;
if (sourceToScan == null) {
patternFounded = false;
} else {
Pattern pattern = Pattern.compile(Pattern.quote(searchPattern),
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(sourceToScan);
patternFounded = matcher.find();
}
return patternFounded;
}
How can i implemented this requirement with regular expressions?
By the way: It is a good solution to check a string, whether it includes numeric content by using the method isNumeric from the java class StringUtils?
//EDIT
The link, which was edited by the admins includes not specific arrangements of characters but only an appearance of characters with regular expressions in general !
After a good while trying to help, answering to constantly changing questions, just found out that the same was asked yesterday, and that the OP doesn't accept answers to his questions...all I have left to say is good night sir, good luck
n-th answer follows:
First pattern: [a-z](-[a-z])* : a letter, possibly followed by more letters, separated by -.
Second pattern: \d+(-\d+)*[?*]* : a number, possibly followed by more numbers, separated by -, and possibly ending with ? or *.
So join them together: ^([a-z](-[a-z])*)|(\d+(-\d+)*[?*]*)$. ^ and $ mark the beginning and the end of the string.
Few more comments on the code: you don't need to use Pattern.quote, and you should use matches() instead of find(), because find() returns true if any part of the string matches the pattern, and you want the whole string:
public static boolean checkPatternMatching(String sourceToScan, String searchPattern) {
boolean patternFounded;
if (sourceToScan == null) {
patternFounded = false;
} else {
Pattern pattern = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(sourceToScan);
patternFounded = matcher.matches();
}
return patternFounded;
}
Called like this: checkPatternMatching(s, "^([a-z](-[a-z])*)|(\\d+(-\\d+)*[?*]*)$")
About the second question, this is the current implementation of StringUtils.isNumeric:
public static boolean isNumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
So no, there is nothing wrong about it, that is as simple as it gets. But you need to include an external JAR in your program, which I find unnecessary if you just want to use such a simple method.
I believe that you should first remove the Pattern.quote() method because that would turn the inputting patterns into string literals; and those are not really useful in your context.
To match the valid arrangements with letters, something like this should work:
^[a-z](?:-[a-z])*$
For the numbers (if I understood the rules correctly):
^\\d+(?:[?*]|-\\d+)*$
And if you want to combine them:
^(?:[a-z](?:-[a-z])*|\\d+(?:[?*]|-\\d+)*)$
I'm not familiar with Java itself, nor the isNumeric method, sorry.
As per your comment, if you want to accept *12 or 1?2 or 12*456, you can use:
^\\*?\\d+(?:[?*]\\d*|-\\d+)*$
Then add it to the previous regex like so:
^(?:[a-z](?:-[a-z])*|\\*?\\d+(?:[?*]\\d*|-\\d+)*)$
I am having issues with this code:
For some reason, it always fails to match the code.
for (int i = 0; i < pluginList.size(); i++) {
System.out.println("");
String findMe = "plugins".concat(FILE_SEPARATOR).concat(pluginList.get(i));
Pattern pattern = Pattern.compile("("+name.getPath()+")(.*)");
Matcher matcher = pattern.matcher(findMe);
// Check if the current plugin matches the string.
if (matcher.find()) {
return !pluginListMode;
}
}
All you really need is
return ("plugins"+FILE_SEPARATOR+pluginName).indexOf(name.getPath()) != -1;
But your code also makes no sense due to the fact that there's no way for that for-loop to enter a second iteration -- it returns unconditionally. So more probably you need something like this:
for (String pluginName : pluginList)
if (("plugins"+FILE_SEPARATOR+pluginName).indexOf(name.getPath()) != -1)
return false;
return true;
Right now we can only guess since we don't know what name.getPath() might return.
I suspect it fails because that string might contain characters that have special meaning inside regexes. Try it again with
Pattern pattern = Pattern.compile("("+Pattern.quote(name.getPath())+")(.*)");
and see what happens then.
Also the (.*) part (and even the parentheses around your name.getPath() result) don't appear to matter at all since you're not doing anything with the result of the match itself. At which point the question is why you're using a regex in the first place.
In Java is there a way to find out if first character of a string is a number?
One way is
string.startsWith("1")
and do the above all the way till 9, but that seems very inefficient.
Character.isDigit(string.charAt(0))
Note that this will allow any Unicode digit, not just 0-9. You might prefer:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
Or the slower regex solutions:
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.
To make the entire condition one line and avoid length checks, you can alter the regexes to the following:
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.
Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
IN KOTLIN :
Suppose that you have a String like this :
private val phoneNumber="9121111111"
At first you should get the first one :
val firstChar=phoneNumber.slice(0..0)
At second you can check the first char that return a Boolean :
firstChar.isInt() // or isFloat()
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}
I just came across this question and thought on contributing with a solution that does not use regex.
In my case I use a helper method:
public boolean notNumber(String input){
boolean notNumber = false;
try {
// must not start with a number
#SuppressWarnings("unused")
double checker = Double.valueOf(input.substring(0,1));
}
catch (Exception e) {
notNumber = true;
}
return notNumber;
}
Probably an overkill, but I try to avoid regex whenever I can.
To verify only first letter is number or character --
For number
Character.isDigit(str.charAt(0)) --return true
For character
Character.isLetter(str.charAt(0)) --return true