How to check is string contains any of special characters? - java

I want to check is some string contains ANY special symbol from UNICODE charset or not. Previosly I harcoded it with regular expression charset, but now list of chars expanded and its not an option to hardcode it now. How to set this check?

You could loop through your string and for every character call, then
public static boolean checkingUnicode(String text){
char[] arr = text.toCharArray();
for(int i=0; i<arr.length; i++){
char c = arr[i];
if(Character.UnicodeBlock.of(c) != Character.UnicodeBlock.BASIC_LATIN){
return true;
}
}
return false;
}
Hope it works

There is an option using Regex.
If it matches regex [a-zA-Z0-9 ] then there is not special characters in it.
Pattern p = Pattern.compile("[a-zA-Z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string");
boolean containsSpecialChar = m.find();
if(containsSpecialChar){
// Do what you need.
}
Hope this will help you.

I think it can be achieve. You need to make a possible list of special characters defined and apply condition in loop for check every character in list for containing that special character.

use the method called Regex.
String s= e2.getText().toString();
Pattern pattern = Pattern.compile("\\d{11}"); //CHANGE PATTERN CONDITIONS ACCORDINGLY
Matcher matcher = pattern.matcher(s); //CHECKS THE PATTERN WITH THE INPUT STRING
if (matcher.matches()) {
// YOUR METHODS
}
else
{
//PRINT AN ERROR TEXT
}

Related

Is there a regex where if first expression is valid then check for next [duplicate]

I have several strings in the rough form:
[some text] [some number] [some more text]
I want to extract the text in [some number] using the Java Regex classes.
I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].
EDIT: I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].
Full example:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
Since you're looking for the first number, you can use such regexp:
^\D+(\d+).*
and m.group(1) will return you the first number. Note that signed numbers can contain a minus sign:
^\D+(-?\d+).*
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex1 {
public static void main(String[]args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("hello1234goodboy789very2345");
while(m.find()) {
System.out.println(m.group());
}
}
}
Output:
1234
789
2345
Allain basically has the java code, so you can use that. However, his expression only matches if your numbers are only preceded by a stream of word characters.
"(\\d+)"
should be able to find the first string of digits. You don't need to specify what's before it, if you're sure that it's going to be the first string of digits. Likewise, there is no use to specify what's after it, unless you want that. If you just want the number, and are sure that it will be the first string of one or more digits then that's all you need.
If you expect it to be offset by spaces, it will make it even more distinct to specify
"\\s+(\\d+)\\s+"
might be better.
If you need all three parts, this will do:
"(\\D+)(\\d+)(.*)"
EDIT The Expressions given by Allain and Jack suggest that you need to specify some subset of non-digits in order to capture digits. If you tell the regex engine you're looking for \d then it's going to ignore everything before the digits. If J or A's expression fits your pattern, then the whole match equals the input string. And there's no reason to specify it. It probably slows a clean match down, if it isn't totally ignored.
In addition to Pattern, the Java String class also has several methods that can work with regular expressions, in your case the code will be:
"ab123abc".replaceFirst("\\D*(\\d*).*", "$1")
where \\D is a non-digit character.
In Java 1.4 and up:
String input = "...";
Matcher matcher = Pattern.compile("[^0-9]+([0-9]+)[^0-9]+").matcher(input);
if (matcher.find()) {
String someNumberStr = matcher.group(1);
// if you need this to be an int:
int someNumberInt = Integer.parseInt(someNumberStr);
}
This function collect all matching sequences from string. In this example it takes all email addresses from string.
static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
public List<String> getAllEmails(String message) {
List<String> result = null;
Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);
if (matcher.find()) {
result = new ArrayList<String>();
result.add(matcher.group());
while (matcher.find()) {
result.add(matcher.group());
}
}
return result;
}
For message = "adf#gmail.com, <another#osiem.osiem>>>> lalala#aaa.pl" it will create List of 3 elements.
Try doing something like this:
Pattern p = Pattern.compile("^.+(\\d+).+");
Matcher m = p.matcher("Testing123Testing");
if (m.find()) {
System.out.println(m.group(1));
}
Simple Solution
// Regexplanation:
// ^ beginning of line
// \\D+ 1+ non-digit characters
// (\\d+) 1+ digit characters in a capture group
// .* 0+ any character
String regexStr = "^\\D+(\\d+).*";
// Compile the regex String into a Pattern
Pattern p = Pattern.compile(regexStr);
// Create a matcher with the input String
Matcher m = p.matcher(inputStr);
// If we find a match
if (m.find()) {
// Get the String from the first capture group
String someDigits = m.group(1);
// ...do something with someDigits
}
Solution in a Util Class
public class MyUtil {
private static Pattern pattern = Pattern.compile("^\\D+(\\d+).*");
private static Matcher matcher = pattern.matcher("");
// Assumptions: inputStr is a non-null String
public static String extractFirstNumber(String inputStr){
// Reset the matcher with a new input String
matcher.reset(inputStr);
// Check if there's a match
if(matcher.find()){
// Return the number (in the first capture group)
return matcher.group(1);
}else{
// Return some default value, if there is no match
return null;
}
}
}
...
// Use the util function and print out the result
String firstNum = MyUtil.extractFirstNumber("Testing4234Things");
System.out.println(firstNum);
Look you can do it using StringTokenizer
String str = "as:"+123+"as:"+234+"as:"+345;
StringTokenizer st = new StringTokenizer(str,"as:");
while(st.hasMoreTokens())
{
String k = st.nextToken(); // you will get first numeric data i.e 123
int kk = Integer.parseInt(k);
System.out.println("k string token in integer " + kk);
String k1 = st.nextToken(); // you will get second numeric data i.e 234
int kk1 = Integer.parseInt(k1);
System.out.println("new string k1 token in integer :" + kk1);
String k2 = st.nextToken(); // you will get third numeric data i.e 345
int kk2 = Integer.parseInt(k2);
System.out.println("k2 string token is in integer : " + kk2);
}
Since we are taking these numeric data into three different variables we can use this data anywhere in the code (for further use)
How about [^\\d]*([0-9]+[\\s]*[.,]{0,1}[\\s]*[0-9]*).* I think it would take care of numbers with fractional part.
I included white spaces and included , as possible separator.
I'm trying to get the numbers out of a string including floats and taking into account that the user might make a mistake and include white spaces while typing the number.
Sometimes you can use simple .split("REGEXP") method available in java.lang.String. For example:
String input = "first,second,third";
//To retrieve 'first'
input.split(",")[0]
//second
input.split(",")[1]
//third
input.split(",")[2]
if you are reading from file then this can help you
try{
InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
//Ref:03
while ((line = br.readLine()) != null) {
if (line.matches("[A-Z],\\d,(\\d*,){2}(\\s*\\d*\\|\\d*:)+")) {
String[] splitRecord = line.split(",");
//do something
}
else{
br.close();
//error
return;
}
}
br.close();
}
}
catch (IOException ioExpception){
logger.logDebug("Exception " + ioExpception.getStackTrace());
}
Pattern p = Pattern.compile("(\\D+)(\\d+)(.*)");
Matcher m = p.matcher("this is your number:1234 thank you");
if (m.find()) {
String someNumberStr = m.group(2);
int someNumberInt = Integer.parseInt(someNumberStr);
}

Regex to convert set of small letters to capital letters in a String

Could someone please tell me how do I write a Regular expression which replaces all the "aeiou" chars found in my string to capital letters like "AEIOU" and vice versa?
I wanted to use replaceAll method of java String class but not sure about the regEx.
This could be the solution.
It seems to me that it has to have Java 9 to use replaceAll method.
Read this Use Java and RegEx to convert casing in a string
public class Main {
public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";
public static void main(String[] args) {
char [] chars = EXAMPLE_TEST.toCharArray(); // trasform your string in a char array
Pattern pattern = Pattern.compile("[aeiou]"); // compile your pattern
Matcher matcher = pattern.matcher(EXAMPLE_TEST); // create a matcher
while (matcher.find()) {
int index = matcher.start(); //index where match exist
chars[index] = Character.toUpperCase(chars[index]); // change char array where match
}
String s = new String(chars); // obtain your new string :-)
//ThIs Is my smAll ExAmplE strIng whIch I'm gOIng tO UsE fOr pAttErn mAtchIng.
System.out.println(s);
}
}
You can use the Pattern and Matcher class, I wrote a quick code it should be clear (subtracting 32 from an ascii alphabetical lower case char will give you its upper case, see the ascii table).
String s = "Anthony";
Pattern pattern = Pattern.compile("[aeiou]");
Matcher matcher = pattern.matcher(s);
String modifiedString = "";
while(matcher.find())
{
modifiedString = s.substring(0, matcher.start()) + (char)(s.charAt(matcher.start()) - 32) + s.substring(matcher.end());
}
System.out.println(modifiedString);

How can I grep same format substrings within a long string by java regular expression?

For example, I want to grep both /css/screen/shared/styles.css and /css/screen/nol/styles.css from this long string:
#import "/css/screen/shared/styles.css";
#import "/css/screen/nol/styles.css";
Note that this long string contains 2 lines, it should look like this in java code:
String sentence = "#import \"/css/screen/nol/styles.css\";\n#import \"/css/screen/shared/styles.css\";";
So far, I have:
"#import\\s\"(.*?)\";\n"
it only identifies the "/css/screen/shared/styles.css", but ignores the "/css/screen/nol/styles.css".
Here is my code:
public static String getImportCSS(String sentence){
String result = "";
if(sentence.length() == 0) return null;
if(sentence.indexOf("#import ") != -1){
Pattern regex = Pattern.compile("#import\\s\"(.*)\";");
Matcher regexMatcher = regex.matcher(sentence);
if(regexMatcher.find()){
for(int i = 0; i <= regexMatcher.groupCount(); i++){
result = regexMatcher.group(1);
}
}
return result;
}
return null;
}
What am I doing wrong here? Thanks!
You cannot match the second string because your regex has an LF (\n) at the end.
Remove it, and the pattern will find both the strings. However, I'd advise to use a negated character class [^"]* (zero or more characters other than a ") rather than a lazy dot matching since the strings should not contain a double quote:
#import\s*\"([^"]*)\";
See the regex demo
Java demo:
String str = "#import \"/css/screen/shared/styles.css\";\n#import \"/css/screen/nol/styles.css\";";
Pattern ptrn = Pattern.compile("#import\\s*\"([^\"]*)\";");
Matcher matcher = ptrn.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}

Java: String.contains matches exact word

In Java
String term = "search engines"
String subterm_1 = "engine"
String subterm_2 = "engines"
If I do term.contains(subterm_1) it returns true. I don't want that. I want the subterm to exactly match one of the words in term
Therefore something like term.contains(subterm_1) returns false and term.contains(subterm_2) returns true
\b Matches a word boundary where a word character is [a-zA-Z0-9_].
This should work for you, and you could easily reuse this method.
public class testMatcher {
public static void main(String[] args){
String source1="search engines";
String source2="search engine";
String subterm_1 = "engines";
String subterm_2 = "engine";
System.out.println(isContain(source1,subterm_1));
System.out.println(isContain(source2,subterm_1));
System.out.println(isContain(source1,subterm_2));
System.out.println(isContain(source2,subterm_2));
}
private static boolean isContain(String source, String subItem){
String pattern = "\\b"+subItem+"\\b";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(source);
return m.find();
}
}
Output:
true
false
false
true
I would suggest using word boundaries. If you compile a pattern like \bengines\b, your regular expression will only match on complete words.
Here is an explanation of word boundaries, as well as some examples.
http://www.regular-expressions.info/wordboundaries.html
Also, here is the java API for the pattern, which does include word boundaries
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Here is an example using your requirements above
Pattern p = Pattern.compile("\\bengines\\b");
Matcher m = p.matcher("search engines");
System.out.println("matches: " + m.find());
p = Pattern.compile("\\bengine\\b");
m = p.matcher("search engines");
System.out.println("matches: " + m.find());
and here is the output:
matches: true
matches: false
If the words are always separated by spaces, this is one way to go:
String string = "search engines";
String[] parts = string.split(" ");
for(int i = 0; i < parts.length; i++) {
if(parts[i].equals("engine")) {
//do whatever you want
}
I want the subterm to exactly match one of the words in term
Then you can't use contains(). You could split the term into words and check equality (with or without case sensitivity).
boolean hasTerm = false;
for (String word : term.split("\\s+") {
if (word.equals("engine")) {
hasTerm = true;
break;
}
}
Use indexOf instead and then check whether char at the poistion
index + length of string plus +1 == ` ` or EOS
or I am sure there is a regex way as well.
Since the contains method verify if does exist that array of char in the string, it will aways return true, you will have to use Regex to make this validation.
If the words are aways separed by space it is easier, you can use the \s regex to get it.
Here is a good tutorial: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
One approach could be to split the string by spaces, convert it to a list, and then use the contains method to check for exact matches, like so:
String[] results = term.split("\\s+");
Boolean matchFound = Arrays.asList(results).contains(subterm_1);
Demo

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