Skip to main content

Regex - Check a text without special characters but German, French

Special characters such as square brackets ([ ]) can cause an exception "java.util.regex.PatternSyntaxException" or something like this if we don't handle them correctly.

I had met this issue. In my case, my customers want our application should allow some characters in German and French even not allow some special characters.

The solution is that we limit the allowed characters by showing the validation message on GUI. For an instance, the message looks like the following:

"This field can't contain any special characters; only letters, numbers, underscores (_), spaces and single quotes (') are allowed."

I used Regular Expression to check it. For entering Germany and French, I actually don't have this type of keyboard, so I referred these sites:

* German characters: http://german.typeit.org/
* French characters: http://french.typeit.org/

Here is my code:
package vn.nvanhuong.practice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpecialCharactersUtil {
 private SpecialCharactersUtil(){}
 
 public static boolean isExistNotAllowedCharacters(String source){
  Pattern regex = Pattern.compile("^[a-zA-Z_0-9_äöüÄÖÜùûüÿàâæéèêëïîôœÙÛÜŸÀÂÆÉÈÊËÏÎÔŒ' ]*$");
  Matcher matcher = regex.matcher(source);
  return !matcher.matches();
 }
}

And, some tests:
package vn.nvanhuong.practice.test;

import static org.junit.Assert.*;

import org.junit.Test;

import vn.nvanhuong.practice.SpecialCharactersUtil;

public class SpecialCharactersUtilTest {

 @Test
 public void shoulDetectSpecialCharacters() {
  String source = "~`!@#$%^&*()-+={}\\[\\]\\|:;\"<>,./?";
  assertTrue(SpecialCharactersUtil.isExistNotAllowedCharacters(source));
 }
 
 @Test
 public void shoulAllowGermanCharacters() {
  String source = "äöüÄÖÜ";
  assertFalse(SpecialCharactersUtil.isExistNotAllowedCharacters(source));
 }
 
 @Test
 public void shoulAllowFrenchCharacters() {
  String source = "ùûüÿàâæéèêëïîôœÙÛÜŸÀÂÆÉÈÊËÏÎÔŒ";
  assertFalse(SpecialCharactersUtil.isExistNotAllowedCharacters(source));
 }

 @Test
 public void shoulAllowAlphanumericAndSpacesAndUnderscoreAndSingleQuote() {
  String source = "character' special_1";
  assertFalse(SpecialCharactersUtil.isExistNotAllowedCharacters(source));
 }
}
Now, we can use the method for our validation on GUI.

Comments

Popular posts from this blog

Small Changes to Java 7 via Project Coin and Why They are Useful

Did you know how new features were added into Java 7? The following are functionalities that can be considered.
Source: [1] Project Coin is all about the changes in the range from syntactic sugar to new language feature. This is what we're talking about today.

Since Java 7 is the first version developed in an open source manner, there is an amount of actions that must be performed for any changes as follows:
Update the Java Language Specification (JSL)Implement a prototype in the source compilerAdd library support essential for the changeWrite tests and examplesUpdate documentEtc, ... Project Coin has submitted a lot of proposals (almost 70) but only some of them are chosen to Java 7. Why? Briefly, Java is a rich static type system and it has a lot of possible interaction points between different bits of it. Making changes to this type system is prone to creating unexpected surprises.

Wow! It is tough, right? Let's take a look what features Project Coin brought to Java 7.
Strings…

Review - The Object-Oriented Thought Process, by Matt Weisfeld

In this post, I would like to point out what I understood after closing my eyes and thinking about what  exactly I have learned from this book. That means the layout of content does not follow the book.
From Procedural to Object Oriented Once upon a time, there is an issue that it is very hard to test and debug in Procedural programming because the data is sometimes global and can be modified by multiple functions.

Object-Oriented (OO) programming addresses these problems by combining both data and functions into an object. That means only functions belong to the object can access its own data.

Let us check the below two different approaches for a case that we want to transfer information between clients and servers across a network.

-    Procedural programming: a client (browser) transfers a JSON data to a server which needs to know how to process with this data. In order words, a handshaking agreement must be defined for the client and server in order to work together.
-    OO prog…

Climbing Fansipan – Highest Peak of Indochina

Fansipan is a mountain in Vietnam, the highest in Indochina, at 3,143 metres. It is located in the Lào Cai Province of the Northwest region of Vietnam, 9 km southwest of Sa Pa Township in the Hoang Lien Son mountain range. Wikipedia
Currently you can get the peak by cable car; however, I loved to explore it by climbing.

Here are what I have learned from this exciting journey. 💪
Do not procrastinate I have had no experience of climbing a high mountain before. Then, I've sought advice from my friends, but they suggested that I should not make it at that time due to bad weather and lack of experience. I know it never come true unless I just make my decision. Can't wait! Prepare for your journey You firstly need getting to know about the journey, schedule, transportation, etc. Recommended sources: YouTube videos, blog posts and tour companies websites.
Tips - Quality hiking shoes helps a lot - Bring your stuffs as light as possible. Important stuffs: a light raincoat and water (t…

Strategy Design Pattern

For example, I have an program with an Animal abstract class and two sub-classes Dog and Bird. I want to add a new behavior for the class Animal, this is "fly".  Now, I face to two approaches to solve this issue:

1. Adding an abstract method "fly" into the class Animal. Then, I force the sub-classes should be implemented this method, something like:

public abstract class Animal{ //bla bla public abstract void fly(); } public class Bird extends Animal{ //bla bla public void fly(){ System.out.println("Fly high"); } } public class Dog extends Animal{ //bla bla public void fly(){ System.out.println("Cant fly"); } }
2. Creating an interfaces with method "fly" inside. The same issue to abstract class, I force the classes these implement this interface should have a method "fly" inside:

public interface Flyable{ public void fly(); } public class Bird implements Flyable{ //bla bla public void fly(){ System.out.println…

Java Core - Top 10 Questions Every Developer Should Know

#RandomlyPickedByMe

What is the difference between Javascript and Java?Difference between StringBuilder and StringBuffer?Why do I get "SomeType@a3fde" when I print my code?Why is String immutable?Why "equals" method when we have "==" operator?Is List<Dog> a subclass of List<Animal>?Why shouldn't we use raw type?Is Java “pass-by-reference” or “pass-by-value”?What's the advantage of a Java enum versus a class with public static final fields?Why "double x = 0.1 + 0.2" and result of print(x) is 0.30000000000000004?
1. What is the difference between Javascript and Java? Holy crap! (Vietnamese: Thế quái nào lại có câu hỏi ngớ ngẩn vậy chứ?)

"Java and Javascript are similar like Car and Carpet are similar." - Greg Hewgill (on StackOverflow)
2. Difference between StringBuilder and StringBuffer String is immutable. StringBuilder and StringBuffer are mutable. StringBuffer is thread-safe. StringBuilder is modern than StringBuff…