Reject String If Contains Any Non-Alpha Numeric Character - java

I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.
I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.
My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.
Sample problematic output:
Please enter a search pattern: /
Line number 1
this.a 2test/austin
^
Line number 8
ra charity Charityis 4 times a day/a.a-A
^
Here is my applicable code:
while (again) {
boolean found = false;
System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
String wordToSearch = input.next();
if (wordToSearch.equals("EINPUT")) {
System.out.printf("%s", "Bye!");
System.exit(0);
}
Pattern p = Pattern.compile("\\W*");
Matcher m = p.matcher(wordToSearch);
if (m.find())
found = true;
String data;
int lineCount = 1;
if (found = true) {
try (FileInputStream fis =
new FileInputStream(this.inputPath.getPath())) {
File file1 = this.inputPath;
byte[] buffer2 = new byte[fis.available()];
fis.read(buffer2);
data = new String(buffer2);
Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
while (in.hasNextLine()) {
String line = in.nextLine();
Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
System.out.println("Line number " + lineCount);
String stringToFile = f.findWords(line, wordToSearch);
System.out.println();
}
lineCount++;
}
}
}
}

Stop reinventing the wheel.
Read this: Apache StringUtils,
Focus on isAlpha,
isAlphanumeric,
and isAlphanumericSpace
One of those is likely to provide the functionality you want.

Create a separate method to call the String you are searching through:
public boolean isAlphanumeric(String str)
{
char[] charArray = str.toCharArray();
for(char c:charArray)
{
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
Then, add the following if statement to the above code prior to the second try statement.
if (isAlphanumeric(wordToSearch) == true)

Well since no one posted REGEX one, here you go:
package com.company;
public class Main {
public static void main(String[] args) {
String x = "ABCDEF123456";
String y = "ABC$DEF123456";
isValid(x);
isValid(y);
}
public static void isValid(String s){
if (s.matches("[A-Za-z0-9]*"))
System.out.println("String doesn't contain non alphanumeric characters !");
else
System.out.println("Invalid characters in string !");
}
}

Right now, what's happening is if the search pattern contains non alphanumeric characters, then do the loop. This is because found = true when the non alphanumeric characters are detected.
if(m.find())
found = true;
What it should be:
if(!m.find())
found = true;
It should be checking for the absence of nonalphanumeric characters.
Also, the boolean flag can just be simplified to:
boolean found = !m.find();
You don't need to use the if statement.

Related

count all valid if statements in .java file

I need to count all valid if statements in a .java file (not commented etc)
I was trying to modify regex for commented items:
(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)
and came up with smth like this:
(?!(([\\(])|(/\\*)|(//)))((?=\\s*))(if)(?=[\\s\\(])
But it doesnt work correctly
Im using this code for test input:
public class Main () {
public static void main (String[] args) {
boolean ifTrue = true;
if (ifTrue == true) {
String wariant = "wariant";
} else if (ifTrue == false) {
String dupa = "variant";
}
//if(ifTrue == true) {
String wariant2 = "This is second wariant";
//}
if(ifTrue) {
if(ifTrue) {
} else if (ifTrue) {
//if ()
/**if*/
}
}
/*if(ifTrue == true) {
String wariant2 = "To jest wariant 2";
}*/
}
}
And this function for counting:
private static int countRegexInInput(String regex, String input) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
For the current sample code , and just counting IF Statements:
/(?:^|\}\s*else)\s+\bif\b/gm
This regex match IF Statements that seems valid. (SEE DEMO)
If your Input texts are general and complex that contains this example:
/* some comments!
if (condition) {
}
*/
use this version:(SEE DEMO)
(?:(?:\/\*)[^]*?\*\/|^)[\s\S]*?(?:^|\}?\s*else)\s*\bif\b
^^1 ^^^^^^^^^^^^^^^2 ^^^^^^3 ^^^^^^^^^^^^^^^^^^^4
Description:
1- match every thing that is Group 2 or is new line ^.
2- find /* and count capturing to */
3- match and pass characters until find new IF
4- IF statement followed by one/many spaces after ^ or after else.
Note: this regex pattern can improve for better matching, if this is not enough!
Well this regex seems to be working for my case:
([^e]\\s)(if)(\\s?\\((\\D[^\\)]+)\\))

Utopian Identification Number - REGEX pattern matching

I'm trying to validate Utopian ID number using java regex classes, ie Pattern and Matcher.
The following are the conditions which needs to be satisfied,
The string must begin with between 0-3 (inclusive) lowercase alphabets.
Immediately following the letters, there must be a sequence of digits (0-9), The length of this segment must be between 2 and 8, both inclusive.
Immediately following the numbers, there must be atleast 3 uppercase letters.
Following is the code which I've written,
public class Solution{public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int ntc;
String[] str;
try {
ntc = Integer.parseInt(br.readLine());
str = new String[ntc];
for (int i = 0; i < ntc; i++)
str[i] = br.readLine();
for (int i = 0; i < ntc; i++)
if (validate(str[i]))
System.out.println("VALID");
else
System.out.println("INVALID");
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean validate(String str) {
Pattern pr = Pattern.compile("[a-z]{0,3}[0-9]{2,8}[A-Z]{3,}");
Matcher mr = pr.matcher(str);
return mr.find();
}}
The following is the input and its respective o/p
I/P:
3
n761512618TUKEFQROSWNFWFWEQEXKPWYYCRK
rRf99
198VLHJIYVEBODQCQEGYGECOGRMQPE
O/P:
VALID
INVALID
VALID
The first testcase is Invalid as it has nine numbers instead of maximum of eight. However it says Valid.
Is there anything wrong in the Regex pattern which I've written.?
Use start and end anchors in your regex in-order to do an exact string match.
Pattern pr = Pattern.compile("^[a-z]{0,3}[0-9]{2,8}[A-Z]{3,}$");
Without anchors, it would match from the middle of a string also.
Use Matcher.matches() rather than Matcher.find(), in order to match the regexp against the entire string:
private static boolean validate(String str) {
Pattern pr = Pattern.compile("[a-z]{0,3}[0-9]{2,8}[A-Z]{3,}");
Matcher mr = pr.matcher(str);
return mr.matches();
}
Also, since the pattern never changes, I would move it into a constant so that it won't be recompiled every time the method is called:
static final Pattern UTOPIAN_ID_PATTERN =
Pattern.compile("[a-z]{0,3}[0-9]{2,8}[A-Z]{3,}");
private static boolean validate(final String str) {
Matcher mr = UTOPIAN_ID_PATTERN.matcher(str);
return mr.matches();
}

How can I make the following regex match my censors? Java

I am trying to censor specific strings, and patterns within my application but my matcher doesn't seem to be finding any results when searching for the Pattern.
public String censorString(String s) {
System.out.println("Censoring... "+ s);
if (findPatterns(s)) {
System.out.println("Found pattern");
for (String censor : foundPatterns) {
for (int i = 0; i < censor.length(); i++)
s.replace(censor.charAt(i), (char)42);
}
}
return s;
}
public boolean findPatterns(String s) {
for (String censor : censoredWords) {
Pattern p = Pattern.compile("(.*)["+censor+"](.*)");//regex
Matcher m = p.matcher(s);
while (m.find()) {
foundPatterns.add(censor);
return true;
}
}
return false;
}
At the moment I'm focusing on just the one pattern, if the censor is found in the string. I've tried many combinations and none of them seem to return "true".
"(.*)["+censor+"](.*)"
"(.*)["+censor+"]"
"["+censor+"]"
"["+censor+"]+"
Any help would be appreciated.
Usage: My censored words are "hello", "goodbye"
String s = "hello there, today is a fine day."
System.out.println(censorString(s));
is supposed to print " ***** today is a fine day. "
Your regex is right!!!!. The problem is here.
s.replace(censor.charAt(i), (char)42);
If you expect this line to rewrite the censored parts of your string it will not. Please check the java doc for string.
Please find below the program which will do what you intend to do. I removed your findpattern method and just used the replaceall with regex in String API. Hope this helps.
public class Regex_SO {
private String[] censoredWords = new String[]{"hello"};
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Regex_SO regex_SO = new Regex_SO();
regex_SO.censorString("hello there, today is a fine day. hello again");
}
public String censorString(String s) {
System.out.println("Censoring... "+ s);
for(String censoredWord : censoredWords){
String replaceStr = "";
for(int index = 0; index < censoredWord.length();index++){
replaceStr = replaceStr + "*";
}
s = s.replaceAll(censoredWord, replaceStr);
}
System.out.println("Censored String is .. " + s);
return s;
}
}
Since this seem like homework I cant give you working code, but here are few pointers
consider using \\b(word1|word2|word3)\\b regex to find specific words
to create char representing * you can write it as '*'. Don't use (char)42 to avoid magic numbers
to create new string which will have same length as old string but will be filled with only specific characters you can use String newString = oldString.replaceAll(".","*")
to replace on-the-fly founded match with new value you can use appendReplacement and appendTail methods from Matcher class. Here is how code using it should look like
StringBuffer sb = new StringBuffer();//buffer for string with replaced values
Pattern p = Pattern.compile(yourRegex);
Matcher m = p.matcher(yourText);
while (m.find()){
String match = m.group(); //this will represent current match
String newValue = ...; //here you need to decide how to replace it
m.appentReplacemenet(sb, newValue );
}
m.appendTail(sb);
String censoredString = sb.toString();

java Exceptions Enter String only

How to catch integer if the user must input String only, no integer and Symbols included to the input? Help me sir for my beginner's report.
import java.util.*;
public class NameOfStudent {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name = "";
System.out.print("Please enter your name: ");
name = input.nextLine(); // How to express error if the Strin contains
//integer or Symbol?...
name = name.toLowerCase();
switch(name)
{
case "cj": System.out.print("Hi CJ!");
break;
case "maria": System.out.print("Hi Maria!");
break;
}
}
}
Use this regular expression.
Check if a String contains number/symbols etc..
boolean result = false;
Pattern pattern = Pattern.compile("^[a-zA-Z]+$");
Matcher matcher = pattern.matcher("fgdfgfGHGHKJ68"); // Your String should come here
if(matcher.find())
result = true;// There is only Alphabets in your input string
else{
result = false;// your string Contains some number/special char etc..
}
Throwing custom exceptions
Throwing custom exceptions in java
Working of a try-catch
try{
if(!matcher.find()){ // If string contains any number/symbols etc...
throw new Exception("Not a perfect String");
}
//This will not be executed if exception occurs
System.out.println("This will not be executed if exception occurs");
}catch(Exception e){
System.out.println(e.toString());
}
I just given a overview, how try-catch works. But you should not use a general "Exception" ever. always use your customized exception for your own exceptions.
Once you have the String in your hand, e.g. name you can apply a regexp to it as follows.
String name = "your string";
if(name .matches(".*\\d.*")){
System.out.println("'"+name +"' contains digit");
} else{
System.out.println("'"+name +"' does not contain a digit");
}
Adapt the logic checks to your needs.
Please be aware that a string can contain numeric character, and it's still a string:
String str = "123";
I think what you meant in your question is "How to enforce alphabetical user input, no numeric or symbol", which can be easily done using regular expression
Pattern pattern = Pattern.compile("^[a-zA-Z]+$"); // will not match empty string
Matcher matcher = pattern.matcher(str);
bool isAlphabetOnly = matcher.find();
Use Regex which is a sequence of characters that forms a search pattern:
Pattern pattern = Pattern.compile("^[a-zA-Z]*$");
Matcher matcher = pattern.matcher("ABCD");
System.out.println("Input String matches regex - "+matcher.find());
Explanation:
^ start of string
A-Z Anything from 'A' to 'Z', meaning A, B, C, ... Z
a-z Anything from 'a' to 'z', meaning a, b, c, ... z
* matches zero or more occurrences of the character in a row
$ end of string
If you also want to check for empty string then replace * with +
If you want to do it without regex then:
public boolean isAlpha(String name)
{
char[] chars = name.toCharArray();
for (char c : chars)
{
if(!Character.isLetter(c))
{
return false;
}
}
return true;
}
You can change your code as follows.
Scanner input=new Scanner(System.in);
System.out.print("Please enter your name: ");
String name = input.nextLine();
Pattern p=Pattern.compile("^[a-zA-Z]*$");// This will consider your
input String or not
Matcher m=p.matcher(name);
if(m.find()){
// your implementation for String.
} else {
System.out.println("Name should not contains numbers or symbols ");
}
Follow this link more about Regex. And test some regex by your self from here.
In Java you formulate what the String is allowed to contain in a regular expression. Then you check if the String contains the allowed sequence - and only the allowed sequence.
Your code looks like this. I've added a do-while-loop to it:
Scanner input = new Scanner(System.in);
String name = "";
do { // get input and check for correctness. If not correct, retry
System.out.print("Please enter your name: ");
name = input.nextLine(); // How to express error if the String contains
//integer or Symbol?...
name = name.toLowerCase();
} while(!name.matches("^[a-z][a-z ]*[a-z]?$"));
// The above regexp allows only non-empty a-z and space, e.g. "anna maria"
// It does not allow extra chars at beginning or end and must begin and end with a-z
switch(name)
{
case "cj": System.out.print("Hi CJ!");
break;
case "maria": System.out.print("Hi Maria!");
break;
}
Now you can change the regular expression, e.g. to allow names with asian character sets. Take a look here how to handle predefined character sets. I was once checking any text for words in any language (and any part of the UTF-8 character set) and ended up with a regular expression like this to find the words in a text: "(\\p{L}|\\p{M})+"
if we want to check that two different user enter same email id while registration.....
public User updateUsereMail(UserDTO updateUser) throws IllegalArgumentException {
System.out.println(updateUser.getId());
User existedUser = userRepository.findOneById(updateUser.getId());
Optional<User> user = userRepository.findOneByEmail(updateUser.getEmail());
if (!user.isPresent()) {
existedUser.setEmail(updateUser.getEmail());
userRepository.save(existedUser);
} else {
throw EmailException("Already exists");
}
return existedUser;
}
Scanner s = new Scanner(System.in);
String name;
System.out.println("enter your name => ");
name = s.next();
try{
if(!name.matches("^[a-zA-Z]+$")){
throw new Exception("is wrong input!");
}else{
System.out.println("perfect!");
}
}catch(Exception e){
System.out.println(e.toString());
}
umm..try storing the values in an array..for each single value , use isLetter() and isDigit() ..then construct a new string with that array
use try catch here and see !
i am not used to Pattern class ,use that if thats' simpler

Check if a String contains a special character

How do you check if a String contains a special character like:
[,],{,},{,),*,|,:,>,
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string");
boolean b = m.find();
if (b)
System.out.println("There is a special character in my string");
If you want to have LETTERS, SPECIAL CHARACTERS and NUMBERS in your password with at least 8 digit, then use this code, it is working perfectly
public static boolean Password_Validation(String password)
{
if(password.length()>=8)
{
Pattern letter = Pattern.compile("[a-zA-z]");
Pattern digit = Pattern.compile("[0-9]");
Pattern special = Pattern.compile ("[!##$%&*()_+=|<>?{}\\[\\]~-]");
//Pattern eight = Pattern.compile (".{8}");
Matcher hasLetter = letter.matcher(password);
Matcher hasDigit = digit.matcher(password);
Matcher hasSpecial = special.matcher(password);
return hasLetter.find() && hasDigit.find() && hasSpecial.find();
}
else
return false;
}
You can use the following code to detect special character from string.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DetectSpecial{
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
System.out.println("Incorrect format of string");
return 0;
}
Pattern p = Pattern.compile("[^A-Za-z0-9]");
Matcher m = p.matcher(s);
// boolean b = m.matches();
boolean b = m.find();
if (b)
System.out.println("There is a special character in my string ");
else
System.out.println("There is no special char.");
return 0;
}
}
If it matches regex [a-zA-Z0-9 ]* then there is not special characters in it.
What do you exactly call "special character" ? If you mean something like "anything that is not alphanumeric" you can use org.apache.commons.lang.StringUtils class (methods IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable).
If it is not so trivial, you can use a regex that defines the exact character list you accept and match the string against it.
This is tested in android 7.0 up to android 10.0 and it works
Use this code to check if string contains special character and numbers:
name = firstname.getText().toString(); //name is the variable that holds the string value
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern number = Pattern.compile("[0-9]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(name);
Matcher matcherNumber = number.matcher(name);
boolean constainsSymbols = matcher.find();
boolean containsNumber = matcherNumber.find();
if(constainsSymbols){
//string contains special symbol/character
}
else if(containsNumber){
//string contains numbers
}
else{
//string doesn't contain special characters or numbers
}
All depends on exactly what you mean by "special". In a regex you can specify
\W to mean non-alpahnumeric
\p{Punct} to mean punctuation characters
I suspect that the latter is what you mean. But if not use a [] list to specify exactly what you want.
Have a look at the java.lang.Character class. It has some test methods and you may find one that fits your needs.
Examples: Character.isSpaceChar(c) or !Character.isJavaLetter(c)
This worked for me:
String s = "string";
if (Pattern.matches("[a-zA-Z]+", s)) {
System.out.println("clear");
} else {
System.out.println("buzz");
}
First you have to exhaustively identify the special characters that you want to check.
Then you can write a regular expression and use
public boolean matches(String regex)
//without using regular expression........
String specialCharacters=" !#$%&'()*+,-./:;<=>?#[]^_`{|}~0123456789";
String name="3_ saroj#";
String str2[]=name.split("");
for (int i=0;i<str2.length;i++)
{
if (specialCharacters.contains(str2[i]))
{
System.out.println("true");
//break;
}
else
System.out.println("false");
}
Pattern p = Pattern.compile("[\\p{Alpha}]*[\\p{Punct}][\\p{Alpha}]*");
Matcher m = p.matcher("Afsff%esfsf098");
boolean b = m.matches();
if (b == true)
System.out.println("There is a sp. character in my string");
else
System.out.println("There is no sp. char.");
//this is updated version of code that i posted
/*
The isValidName Method will check whether the name passed as argument should not contain-
1.null value or space
2.any special character
3.Digits (0-9)
Explanation---
Here str2 is String array variable which stores the the splited string of name that is passed as argument
The count variable will count the number of special character occurs
The method will return true if it satisfy all the condition
*/
public boolean isValidName(String name)
{
String specialCharacters=" !#$%&'()*+,-./:;<=>?#[]^_`{|}~0123456789";
String str2[]=name.split("");
int count=0;
for (int i=0;i<str2.length;i++)
{
if (specialCharacters.contains(str2[i]))
{
count++;
}
}
if (name!=null && count==0 )
{
return true;
}
else
{
return false;
}
}
Visit each character in the string to see if that character is in a blacklist of special characters; this is O(n*m).
The pseudo-code is:
for each char in string:
if char in blacklist:
...
The complexity can be slightly improved by sorting the blacklist so that you can early-exit each check. However, the string find function is probably native code, so this optimisation - which would be in Java byte-code - could well be slower.
in the line String str2[]=name.split(""); give an extra character in Array...
Let me explain by example
"Aditya".split("") would return [, A, d,i,t,y,a] You will have a extra character in your Array...
The "Aditya".split("") does not work as expected by saroj routray you will get an extra character in String => [, A, d,i,t,y,a].
I have modified it,see below code it work as expected
public static boolean isValidName(String inputString) {
String specialCharacters = " !#$%&'()*+,-./:;<=>?#[]^_`{|}~0123456789";
String[] strlCharactersArray = new String[inputString.length()];
for (int i = 0; i < inputString.length(); i++) {
strlCharactersArray[i] = Character
.toString(inputString.charAt(i));
}
//now strlCharactersArray[i]=[A, d, i, t, y, a]
int count = 0;
for (int i = 0; i < strlCharactersArray.length; i++) {
if (specialCharacters.contains( strlCharactersArray[i])) {
count++;
}
}
if (inputString != null && count == 0) {
return true;
} else {
return false;
}
}
Convert the string into char array with all the letters in lower case:
char c[] = str.toLowerCase().toCharArray();
Then you can use Character.isLetterOrDigit(c[index]) to find out which index has special characters.
Use java.util.regex.Pattern class's static method matches(regex, String obj)
regex : characters in lower and upper case & digits between 0-9
String obj : String object you want to check either it contain special character or not.
It returns boolean value true if only contain characters and numbers, otherwise returns boolean value false
Example.
String isin = "12GBIU34RT12";<br>
if(Pattern.matches("[a-zA-Z0-9]+", isin)<br>{<br>
System.out.println("Valid isin");<br>
}else{<br>
System.out.println("Invalid isin");<br>
}

Categories