Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String validation

Status
Not open for further replies.

hbutt

Programmer
Apr 15, 2003
35
GB
hi there,
just wanted to know how to validate a string, i.e. if the string characters other than capitals A-Z then an error message will be printed to the screen. e.g.

string = "HeLLO" => ERROR!
string = "HELLO WORLD" =>WRONG!
string = "HELLOWORLD" => CORRECT!

thanx
hgsb
 
any further help? i aint to clever with the regex
 
Code:
for (int i = 0; i < str.length();i++) {
   if ((str.charAt(i) < 'A') || (str.charAt(i) > 'Z')) {
      return (false);
   }
   return (true);
}

Set up that little snippet of code inside a function, or method if you are creating your own String subclass.

-kaht
 
An example of using a pattern to validate the string..

import java.io.*;

public final class RegexTestHarness {
public static void main(String[] argv){

String testString = &quot;HeLLO&quot;;
if(testString.matches(&quot;^[A-Z]+$&quot;))
System.out.println(testString + &quot; is valid.&quot;);
else
System.out.println(testString + &quot; is invalid.&quot;);

testString = &quot;HELLO WORLD&quot;;
if(testString.matches(&quot;^[A-Z]+$&quot;))
System.out.println(testString + &quot; is valid.&quot;);
else
System.out.println(testString + &quot; is invalid.&quot;);

testString = &quot;HELLOWORLD&quot;;
if(testString.matches(&quot;^[A-Z]+$&quot;))
System.out.println(testString + &quot; is valid.&quot;);
else
System.out.println(testString + &quot; is invalid.&quot;);
}
}
 
A brief explaination of the pattern used..

^[A-Z]+$

^ = Start of a string.
[A-Z] = character between A to Z
+ = 1 or more of previous expression
$ = end of string
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top