Google

Jun 30, 2013

Core Java Coding Interview Question -- validating an input String to be alphanumeric

Q. Can you write sample code as to different ways in which you can validate an input String to return true if the input is alpha numeric and otherwise return false?
A. It can be done a number of different ways.
  1. Using regex.
  2. Without using regex.
 Firstly, using regex

Step 1: Have the right dependency jars in the pom.xml file as shown below.

<dependency>
 <groupId>commons-lang</groupId>
 <artifactId>commons-lang</artifactId>
 <version>2.6</version>
</dependency>

<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.10</version>
 <scope>test</scope>
</dependency>


Step 2: The implementation class.

package com.mycompany.app5;

import org.apache.commons.lang.StringUtils;

public class AlphaNumeric
{
    
    public boolean isAlphaNumeric(String input)
    {
        //fail fast
        if (StringUtils.isEmpty(input))
        {
            throw new IllegalArgumentException("The input cannot be empty !!!");
        }
        
        boolean result = false;
        
        if (input.matches("[a-zA-Z0-9]+")) // one or more alpha numeric characters
        {
            result = true;
        }
        
        return result;
        
    }
}


Step 3:The JUnit test class.

package com.mycompany.app5;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

public class AlphaNumericTest
{ 
    AlphaNumeric an;
    
    @Before
    public void setUp()
    {
        an = new AlphaNumeric();
    }
    
    @Test
    public void testAlphaNumericHappyPath()
    {
        Assert.assertEquals(true, an.isAlphaNumeric("AUD123"));
        Assert.assertEquals(true, an.isAlphaNumeric("123aud"));
        Assert.assertEquals(true, an.isAlphaNumeric("123"));
        Assert.assertEquals(true, an.isAlphaNumeric("hgD"));
        
        Assert.assertEquals(false, an.isAlphaNumeric("hg*D"));
        Assert.assertEquals(false, an.isAlphaNumeric("@hgD"));
        Assert.assertEquals(false, an.isAlphaNumeric("@hgD"));
        Assert.assertEquals(false, an.isAlphaNumeric("@*#"));
    }
    
    @Test(expected = java.lang.IllegalArgumentException.class)
    public void testAlphaNumericUnHappyPath1()
    {
        Assert.assertEquals(true, an.isAlphaNumeric(null));
    }
    
    @Test(expected = java.lang.IllegalArgumentException.class)
    public void testAlphaNumericUnHappyPath2()
    {
        Assert.assertEquals(true, an.isAlphaNumeric(""));
    }
}

Using apache's commons-lang package's method directly as shown below.

package com.mycompany.app5;

import org.apache.commons.lang.StringUtils;

public class AlphaNumeric
{
    
    public boolean isAlphaNumeric(String input)
    {
        //fail fast
        if (StringUtils.isEmpty(input))
        {
            throw new IllegalArgumentException("The input cannot be empty !!!");
        }
        
        boolean result = false;
        
        if (StringUtils.isAlphanumeric(input)) // one or more alpha numeric characters
        {
            result = true;
        }
        
        return result;
        
    }
}

Using the core Java without any framework

package com.mycompany.app5;

import org.apache.commons.lang.StringUtils;

public class AlphaNumeric
{
    
    public boolean isAlphaNumeric(String input)
    {
        //fail fast
        if (StringUtils.isEmpty(input))
        {
            throw new IllegalArgumentException("The input cannot be empty !!!");
        }
        
        boolean result = true;
        
        //chack each character agaianst the ASCII table hex value
        for (int i = 0; i < input.length(); i++)
        {
            char c = input.charAt(i);
            if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
            {
                result = false;
                break;
            }
        }
        
        return result;
        
    }
}

Alternatively, using the Character class.

package com.mycompany.app5;

import org.apache.commons.lang.StringUtils;

public class AlphaNumeric
{
    
    public boolean isAlphaNumeric(String input)
    {
        //fail fast
        if (StringUtils.isEmpty(input))
        {
            throw new IllegalArgumentException("The input cannot be empty !!!");
        }
        
        boolean result = true;
        
        //chack each character agaianst the ASCII table hex value
        for (int i = 0; i < input.length(); i++)
        {
            char c = input.charAt(i);
            if (!Character.isDigit(c) && !Character.isLetter(c))
            {
                result = false;
                break;
            }
        }
        
        return result;
        
    }
}

Labels: ,

Jun 20, 2013

Notepad++ with power of regex as a productivity tool for developers

This is an extension to my post entitled Notepad++ plugin for viewing JSON data and other benefits to demonstrate the power of Notepad++ and regular expression.

This post is based on a industrial example where you have a CSV file where you want to add quotes (i.e. ") around it. For example

Convert text like:

 
BA555,04-May-2013,04-04-2013,12358,AUSTRALIAN BONDS,,86776.00,AUD,86776,Application,,Capital


To

"BA555","04-May-2013","04-04-2013","12358","AUSTRALIAN BONDS","","86776.00","AUD","86776","Application","","Capital"

Another reason you might want to do this in Java is to construct a String array or list as shown below.

       List<string> asList = Arrays.asList(new String[]
        {
            "BA555", "04-May-2013", "04-04-2013", "12358", "AUSTRALIAN BONDS", "", "86776.00", "AUD", "86776",
            "Application", "", "Capital"
        });

Now let's see how we can use notepad++ find/replace function to add quotes around each entry using its find/replace with regular expressions as shown below.


As you can see

Find what regular expression is:  ([^,]*)(,?) , which means 0 or more characters but "," as first group stored in "\1" followed by 0 or 1 "," (i.e. optional ,), and grouped as \2.

Replace with regular expression is: "\1"\2 where " is added then followed by \1, which is the value captured like BA555 and then followed by ", and followed by optional ",".

Similar approaches can be used for formatting other bulk records like removing spaces, adding quotes, replacing new line characters with tabs, replacing tabs with new lines, replacing commas with new lines, etc.

Here is an example for replacing "," with new lines.



The output will be

 
BA555
04-May-2013
04-04-2013
12358
AUSTRALIAN BONDS

86776.00
AUD
86776
Application

Capital

Labels: ,

Jun 14, 2013

The power of regular expression and testing tools like regexpal.com

Regular expressions are also known as regex, and they are very powerful and used widely in JavaScript, Unix scripting,  development tools, monitoring tools like Tivoli, and programming languages. So, it really pays to have good knowledge of regexes. This post is about a handy tool named "regexpal.com" that helps you not only learn regex, but also to quickly verify your regexes while working on a project. If you google for "regex online validator" you will find other similar online validating tools.



Step 1: Open up a browser and type regexpal.com on the address bar. Yo will get the online validator.

Step 2: Type or copy/paste the regex at the top window and the text to apply the regex on the second window.


As indicated in the footer, use RegexBuddy for a more powerful regex testing. The regex keywords are highlighted in blue. Also the matched phrase is also highlighted. In blue for the exact match and in yellow for any other string match.

The above example matches any string followed by one of "Monitoring", "MYAPP", or "CASHFORECAST". The "|" in regex means "OR". What if you want to literally match "Monitoring|MYAPP|CASHFORECAST"? You can escape "|" with "\" as shown below.


Now, the  "|" is not highlighted in blue as it is escaped.

Change the text as shown below. The "CASHFORECAST" is changed to "TRADEFORECAST" and match is no longer found as the text is not highlighted.

Labels: ,