Java String Validation and Scrubbing

I find myself more and more needing to validate user input, checking for illegal characters and empty Strings.

import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ScrubTest {
 
	public String scrubText(String dirty) {
		dirty = scrub("\\s+", dirty, " ");
		return scrub("^\\s?|\\s?$", dirty, "");
	}
 
	public String scrub(String pattern, String text, String replace) {
		Pattern p = Pattern.compile(pattern);
		Matcher matcher = p.matcher(text);
		return matcher.replaceAll(replace);
	}
 
	public static void main(String[] args) {
 
		ScrubTest st = new ScrubTest();
		LinkedList<String> list = new LinkedList<String>();
 
		list.add(new String("test"));
		list.add(null);
		list.add(new String(""));
		list.add(new String(" "));
		list.add(new String("\n"));
 
		for (String s : list) {
			System.out.println ("\nTesting string: \"" + s + "\"\n---------------");
			try {
				s = st.scrubText(s);
				System.out.println ("null:  " + (s == null));
				System.out.println ("empty: " + s.isEmpty());
				System.out.println ("\\n:    " + s.equalsIgnoreCase("\n"));
			}
			catch (Exception e) {
				System.out.println ("ERROR:" + e);
			}
		}
 
		String scrubbed = "\n\n\n   This   is       just a  test            \n    ";
		scrubbed = st.scrubText(scrubbed);
 
		System.out.println (scrubbed + ".");
	}
}

Produces:

Testing string: "test"
---------------
null:  false
empty: false
\n:    false

Testing string: "null"
---------------
ERROR:java.lang.NullPointerException

Testing string: ""
---------------
null:  false
empty: true
\n:    false

Testing string: " "
---------------
null:  false
empty: true
\n:    false

Testing string: "
"
---------------
null:  false
empty: true
\n:    false
This is just a test.

2 Responses to “Java String Validation and Scrubbing”

  1. Ivan says:

    Very nice! I am working with this a little bit more to see if I need to extend it.

  2. kyle says:

    @Ivan
    I’m sure there are better ways to do this. It’s mostly a reminder to myself how Pattern and Matcher work.

Leave a Reply

 

Staypressed theme by Themocracy