A regular expression to detect a blank string...

Anyone know how to write a regular expression that will detect a blank string?
I.e., in a webservice xsd I'm adding a restriction to stop the user specifying a blank string for an element in the webservice operation call.
But I can't figure out a regular expression that will detect an entirely blank string but that will on the other hand allow the string to contain blank spaces in the text.
So the restriction should not allow "" or " " to be specified but will allow "Joe Bloggs" to be specified.
I tried [^ ]* but this wont allow "Joe Bloggs" to pass.
Any ideas?
Thanks,
Ruairi.

Hi ruairiw,
there is a shortcut for the set of whitespace chars in Java. It is the Expression *\s* which is equal to *[ \t\n\f\r\u000b]*.
With this expression you can test whether a String consists only of whitespace chars.
Expamle:
String regex = "\\s*"; // the slash needs to be escaped
// same as String regex = "[ \t\n\f\r\u000b]";
System.out.println("".matches(regex)); // true
System.out.println("   ".matches(regex)); // true
System.out.println("  \r\n\t ".matches(regex)); // true
System.out.println("\n\nTom".matches(regex)); // false
System.out.println("   Tom Smith".matches(regex)); // falseBesh Wishes
esprimo

Similar Messages

  • How to specify ");" as a regular expression in split method of String class

    How to specify ");" as a regular expression in split method of String class using delimeters?

    Sorry, you can't specify that by using delimiters. Mostly because this requirement makes no sense.
    Do you rather need "\\);"?

  • OR ('|') in regular expressions (e.g. split a String into lines)

    Which match gets used when you use OR ('|') to specify multiple possible matches in a regex, and there are multiple matches among the supplied patterns? The first one (in the order written) which matches? Or the one which matches the most characters?
    To make this concrete, suppose that you want to split a String into lines, where the line delimiters are the same as the [line terminators used by Java regex|http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#lt] :
         A newline (line feed) character ('\n'),
         A carriage-return character followed immediately by a newline character ("\r\n"),
         A standalone carriage-return character ('\r'),
         A next-line character ('\u0085'),
         A line-separator character ('\u2028'), or
         A paragraph-separator character ('\u2029)
    This problem has [been considered before|http://forums.sun.com/thread.jspa?forumID=4&threadID=464846] .
    If we ignore the idiotic microsoft two char \r\n sequence, then no problem; the Java code would be:
    String[] lines = s.split("[\\n\\r\\u0085\\u2028\\u2029]");How do we add support for \r\n? If we try
    String[] lines = s.split("[\\n\\r\\u0085\\u2028\\u2029]|\\r\\n");which pattern of the compound (OR) regex gets used if both match? The
    [\\n\\r\\u0085\\u2028\\u2029]or the
    \\r\\n?
    For instance, if the above code is called when
    s = "a\r\nb";and if the first pattern
    [\\n\\r\\u0085\\u2028\\u2029]is used for the match when the \r is encountered, then the tokens will be
    "a", "", "b"
    because there is an empty String between the \r and following \n. On the other hand, if the rule is use the pattern which matches the most characters, then the
    \\r\\n
    pattern will match that entire \r\n and the tokens will be
    "a", "b"
    which is what you want.
    On my particular box, using jdk 1.6.0_17, if I run this code
    String s = "a\r\nb";
    String[] lines = s.split("[\\n\\r\\u0085\\u2028\\u2029]|\\r\\n");
    System.out.print(lines.length + " lines: ");
    for (String line : lines) System.out.print(" \"" + line + "\"");
    System.out.println();
    if (true) return;the answer that I get is
    3 lines:  "a" "" "b"So it seems like the first listed pattern is used, if it matches.
    Therefore, to get the desired behavior, it seems like I should use
    "\\r\\n|[\\n\\r\\u0085\\u2028\\u2029]"instead as the pattern, since that will ensure that the 2 char sequence is first tried for matches. Indeed, if change the above code to use this pattern, it generates the desired output
    2 lines:  "a" "b"But what has me worried is that I cannot find any documentation concerning this "first pattern of an OR" rule. This means that maybe the Java regex engine could change in the future, which is worrisome.
    The only bulletproof way that I know of to do line splitting is the complicated regex
    "(?:(?<=\\r)\\n)" + "|" + "(?:\\r(?!\\n))" + "|" + "(?:\\r\\n)" + "|" + "\\u0085" + "|" + "\\u2028" + "|" + "\\u2029"Here, I use negative lookbehind and lookahead in the first two patterns to guarantee that they never match on the end or start of a \r\n, but only on isolated \n and \r chars. Thus, no matter which order the patterns above are applied by the regex engine, it will work correctly. I also used non-capturing groups
    (?:X)
    to avoid memory wastage (since I am only interested in grouping, and not capturing).
    Is the above complicated regex the only reliable way to do line splitting?

    bbatman wrote:
    Which match gets used when you use OR ('|') to specify multiple possible matches in a regex, and there are multiple matches among the supplied patterns? The first one (in the order written) which matches? Or the one which matches the most characters?
    The longest match wins, normally. Except for alternation (or) as can be read from the innocent sentence
    The Pattern engine performs traditional NFA-based matching with ordered alternation as occurs in Perl 5.
    in the javadocs. More information can be found in Friedl's book, the relevant page of which google books shows at
    [http://books.google.de/books?id=GX3w_18-JegC&pg=PA175&lpg=PA175&dq=regular+expression+%22ordered+alternation%22&source=bl&ots=PHqgNmlnM-&sig=OcDjANZKl0VpJY0igVxkQ3LXplg&hl=de&ei=Dcg7S43NIcSi_AbX-83EDQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CA0Q6AEwAA#v=onepage&q=&f=false|http://books.google.de/books?id=GX3w_18-JegC&pg=PA175&lpg=PA175&dq=regular+expression+%22ordered+alternation%22&source=bl&ots=PHqgNmlnM-&sig=OcDjANZKl0VpJY0igVxkQ3LXplg&hl=de&ei=Dcg7S43NIcSi_AbX-83EDQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CA0Q6AEwAA#v=onepage&q=&f=false]
    If this link does not survive, search google for
    regular expression "ordered alternation"
    My first hit went right into Friedl's book.
    Harald.

  • Using Regular Expressions to replace Quotes in Strings

    I am writing a program that generates Java files and there are Strings that are used that contain Quotes. I want to use regular expressions to replace " with \" when it is written to the file. The code I was trying to use was:
    String temp = "\"Hello\" i am a \"variable\"";
    temp = temp.replaceAll("\"","\\\\\"");
    however, this does not work and when i print out the code to the file the resulting code appears as:
    String someVar = ""Hello" i am a "variable"";
    and not as:
    String someVar = "\"Hello\" i am a \"variable\"";
    I am assumming my regular expression is wrong. If it is, could someone explain to me how to fix it so that it will work?
    Thanks in advance.

    Thanks, appearently I'm just doing something weird that I just need to look at a little bit harder.

  • Regular expression - get longest number from string

    I believe it is easy one but I can't get it.Lets say I have a string 'A1_1000' I want to substract the 1000 using regular expression. When I feed Match regular expression I get '1' which is not the longest number. I know other ways of doing that but I want clean solution in one step. Does anybody knows the right regular expression to accomplish that? Thanks!
    LV 2011, Win7
    Solved!
    Go to Solution.

    ceties wrote:
    This is the best solution I was able to come with. I am just wondering if there is "smoother way" without the cycle.
    Since multiple checks are required I would tend to beieve that we do have to loop through the possibilities. in this example
    I start check at offset "0" into the string for a number. Provided i find a number I check if it is longer that any previous number I found and if so save the new longer number in the shift register.
    Have fun!
    Ben
    Message Edited by Ben on 04-15-2009 09:23 AM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Attachments:
    Find_Longest.PNG ‏33 KB

  • Unique regular expression to check if a string contains letters and numbers

    Hi all,
    How can I verify if a string contains numbers AND letters using a regular expression only?
    I can do that with using 3 different expressions ([0-9],[a-z],[A-Z]) but is there a unique regular expression to do that?
    Thanks all

    Darin.K wrote:
    Missed the requirements:
    single regex:
    ^([[:alpha:]]+[[:digit:]]+|[[:digit:]]+[[:alpha:]])[[:alnum:]]*$
    You either have 1 or more digits followed by 1 or more letters or 1 or more letters followed by 1 or more digits. Once that is out of the way, the rest of the string must be all alphanumerics.  The ^ and $ make sure the whole string is included in the match.
    (I have not tested this at all, just typed it up hopefully I got all the brackets in the right place).
    I think you just made my point.  TWICE.  While the lex class would be much more readable as a ring.... I know all my brackets are in the correct places and don't need to hope.
    Jeff

  • Cannot get regular expression to return true in String.matches()

    Hi,
    My String that I'm attempting to match a regular expression against is: value=='ORIG')
    My regular expression is: value=='ORIG'\\) The double backslashes are included as a delimiter for ')' which is a regular expression special character
    However, when I call the String.matches() method for this regular expression it returns false. Where am I going wrong?
    Thanks.

    The string doesn't contain what you think it contains, or you made a mistake in your implementation.
    public class Bar {
       public static void main(final String... args) {
          final String s = "value=='ORIG')";
          System.out.println(s.matches("value=='ORIG'\\)")); // Prints "true"
    }

  • Regular expression to get substring from string

    Hi,
    I’m having the following problem:
    SELECT REGEXP_SUBSTR(';first field;ir-second field-02;ir-second field-01; third field','.*ir-(.*)-01.*’)FROM dual
    [\CODE]
    This is the select that I have with a java expression!
    In java I’m able to do find the right expression to retrieve what I want, but I don’t know how to adapt this for oracle!
      In oracle I was trying to do something like this:
    NVL(SUBSTR(REGEXP_SUBSTR(CONCAT(';', list),';ir-[^01;]+'),LENGTH(';ir-')+1,LENGTH(REGEXP_SUBSTR(CONCAT(';',list),';ir-[^01;]+'))), ' ') AS result
    [\CODE]
    But it doesn’t work because “ir” can repeat in other parameters.
    “ir-something-01” only appears once.
    Is it in oracle a logic similar to result groups in oracle?
    best regards,
    Ricardo Tomás

    rctomas wrote:
    Hi,
    In java I’m able to do find the right expression to retrieve what I wantWell, would be nice to tell us what that right expression would be :). Anyway, is this what you are looking for:
    SQL> SELECT REGEXP_SUBSTR(';first field;ir-second field-02;ir-second field-01; third field',';ir-([^;]*)-01')
      2  from dual
      3  /
    REGEXP_SUBSTR(';FIR
    ;ir-second field-01
    SQL> SY.

  • Regular expression help please. (extractin​g a string subset between two markers)

    I haven't used regular expressions before, and I'm having trouble finding a regular expression to extract a string subset between two markers.
    The string;
    Header stuff I don't want
    Header stuff I don't want
    Header stuff I don't want
    Header stuff I don't want
    Header stuff I don't want
    Header stuff I don't want
    ERRORS 6
    Info I want line 1
    Info I want line 2
    Info I want line 3
    Info I want line 4
    Info I want line 5
    Info I want line 6
    END_ERRORS
    From the string above (this is read from a text file) I'm trying to extract the string subset between ERRORS 6 and END_ERRORS. The number of errors (6 in this case) can be any number 1 through 32, and the number of lines I want to extract will correspond with this number. I can supply this number from a calling VI if necessary.
    My current solution, which works but is not very elegant;
    (1) uses Match Regular Expression to the return the string after matching ERRORS 6
    (2) uses Match Regular Expression returning all characters before match END_ERRORS of the string returned by (1)
    Is there a way this can be accomplished using 1 Match Regular Expression? If so could anyone suggest how, together with an explanation of how the regular expression given works.
    Many thanks
    Alan
    Solved!
    Go to Solution.

    I used a character class to catch any word or whitespace characters.  Putting this inside parentheses makes a submatch that you can get by expanding the Match Regular Expression node.  The \d finds digits and the two *s repeat the previous term.  So, \d* will find the '6', as well as '123456'.
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice

  • Evaluating a String True/False with a Regular Expression

    I need to write a regular expression to make the following strings display the values of true/false:
    112 Elm Street True
    112 South Elm St. True
    112 S. Elm True
    Elm St. False
    South 112 Elm False
    Here's what I have so far:
    public class MethodOne
         public static void main (String args[])
              return street.matches (//d+//s+[A-Z]{1}[a-z][.]?//s{1}[A-Z]{1}[a-z]+[.]);
            String address1 = "112 Elm Address"
            String address2 = "112 South Elm St."
            String address3 = "112 S. Elm"
            String address4 = "Elm St."
            String address5 = "South 112 Elm"
            if (address1.matches(street) ) {
            System.out.println("True");
            else {
            System.out.println("False")
               }// end if
         Can anyone help me out?

    Is this what you want?
    String address1 = "112 Elm Street";
    String address2 = "112 South Elm St.";
    String address3 = "112 S. Elm";
    String address4 = "Elm St.";
    String address5 = "South 112 Elm";
    String matchString = "\\d+ [A-Z,a-z,. ]+";
    System.out.println(address1.matches(matchString));
    System.out.println(address2.matches(matchString));
    System.out.println(address3.matches(matchString));
    System.out.println(address4.matches(matchString));
    System.out.println(address5.matches(matchString));

  • How to create a list of string if a regular expression is given ?

    Hi folks,
    I have a regular expression say abcd[a-z]\\\.[0-9] . ( please ignore one '\')
    For this string i know that
    following string matches successfully
    1. abca.0
    2. abcb.1
    3. abcz.9 ......etc n number of combination are possible.
    is there any algorithm which will create some randomn strings from a regular expression.
    input to algorithm : some string pattern
    output to algorithm : some matching strings ( can be a single or an array of matching strings)
    Thanks in advance..
    Sethu
    Edited by: Sethumadhavan on Apr 16, 2008 6:32 AM

    Can u please give little more explanation...
    If i get some some values i can exit with the values ... and from the values i got i can ignore the duplicates ...
    But i am not getting the basic algorithm to get list of strings.....( DFA? or NFA?)
    thanks
    sethu

  • Using Regular Expressions for Completion

    I'm trying to build a text completer for a simple little editor. The general idea is that I have a regular expression which describes the syntax of an expression and a set of strings which are all semantically valid cases of the expression (the latter of which is not particularly important to my problem). I would like to be able to determine, using the expression described, whether or not a section of text is capable of beginning a syntactically valid expression, not matching it.
    For example, given the expression
    "#[A-Za-z0-9]#" the string "#name#" is syntactically valid, whereas the string "#_blarg" is not. What I would like to do is be able to determine that "#partial" has the potential to match the pattern with more input, even if it doesn't yet. Specifically, the eventual use will be in such a case as the string X=#partial+3. If the cursor is positioned before the "+" and my user presses the completion keystroke, I want to recognize that "#partial" is what I need to recognize. Also, positioning the cursor immediately after the "=" and pressing the keystroke will do nothing, since nothing before the "=" is capable of matching the pattern properly.
    Is this possible? I don't have to use this exact approach, but it is important that I be able to use the regular expression in detecting a partially completed expression. If I can, the set of regular expressions which already exist in the code can be used to drive the auto completer. Otherwise, I'll have to write a special recognition module for each case; that wouldn't be pretty.
    Thanks for your time! I'll provide other information upon request, if it'd help. :)

    Thank you both for discussing this; it has definitely helped me in reaching a better understanding of uncle_alice's answer to my problem. I've adjusted my code to use this approach and, for the most part, it seems to work.
    I say "for the most part" because I am compiling Patterns with the case insensitivity flag. This appears to do horrible, horrible things. Take a look at the following code, modified from uncle_alice's example:
    String[] str = {"#test#hello", "#tes", "blargblarg", "", "#test#", "S"};
    String rgx = "#[A-Za-z0-9]+#";
    Pattern pc = Pattern.compile(rgx);
    Pattern pi = Pattern.compile(rgx, Pattern.CASE_INSENSITIVE);
    for (String s : str)
        System.out.println("    For string: "+s);
        for (Pattern p : new Pattern[]{pc, pi}) // once for each pattern
            Matcher m = p.matcher(s);
            if (m.matches())
                System.out.printf("Matched '%s'", m.group());
            } else
                System.out.print("No match");
            System.out.println("; hitEnd = " + m.hitEnd());
    }That produces the following output:
        For string: #test#hello
    No match; hitEnd = false
    No match; hitEnd = true
        For string: #tes
    No match; hitEnd = true
    No match; hitEnd = true
        For string: blargblarg
    No match; hitEnd = false
    No match; hitEnd = true
        For string:
    No match; hitEnd = true
    No match; hitEnd = true
        For string: #test#
    Matched '#test#'; hitEnd = false
    Matched '#test#'; hitEnd = false
        For string: S
    No match; hitEnd = false
    No match; hitEnd = trueIt would seem that, with the case-insensitive flag set, hitEnd always returns true unless a match is found. Why is this? I find it quite confusing.
    I can adjust my design to accomodate if this problem cannot be circumvented; however, I'd like to understand what has going wrong here. :)
    Cheers! Thanks so much for all your help!

  • Regular Expression for match pattern

    Hi guys, I need some help.
    In one part of my test system, I give to the program a sequence of temperatures, which are numbers separated by a comma. Due to a possible error, the user can  forget the coma, and the program gets unexpected values.
    For example, "20, 70, -10" is a right value, whereas "20 70, -10" would be a wrong one.
    Which regular expression will detect this comma absence?
    Thanx in advance.

    OK, makes it more difficult (and more fun )
    My original version failed also when the space was forgotten.  DOH!
    Try this version.  It get's complicated cause the scan from string likes ignoring spaces... So we change the spaces
    Hope this helps
    Shane.
    PS The ideas given by others are still a better solution, but if you're stuck........
    Using LV 6.1 and 8.2.1 on W2k (SP4) and WXP (SP2)
    Attachments:
    Check input string with commas(array).vi ‏39 KB

  • Regular Expression for PathName???

    Anyone have a "ready to go" regular expression for detecting a pathname?
    for example I need to detect the following:
    myfile.txt
    ./myfile.txt
    ../my-file.ini
    /home/my-home/myFile.foo
    etc.
    Now, in a perfect world, it could also do Windows (or ANY OS for that matter) pathnames (though this is not terrbibly important for my case at least).
    TIA,
    /m

    import java.util.regex.*;
    * @author  Ian Schneider
    public class FileRegex {
        static Pattern pattern;
        /** Creates a new instance of FileRegex */
        public FileRegex() {
        public Pattern getPattern() {
            if (pattern == null) {
                pattern = Pattern.compile("([\\/]?(\\w+|\\.|\\.\\.)[\\/])*(\\w+)\\.?(\\w+)?");
            return pattern;
        public String[] parts(String path) {
            Matcher m = getPattern().matcher(path);
            if (m.find()) {
                return new String[] { m.group(1),m.group(3),m.group(4) };
            return null;
        public boolean matches(String path) {
            return getPattern().matcher(path).matches();
        public static final void main(String[] args) throws Exception {
            FileRegex regex = new FileRegex();
            String[] files = {
                "myfile.txt",
                "../myfile.txt",
                "./myfile.txt",
                "/a/b/c/myfile.txt",
                "/a/../myfile.txt",
                "myfile"
            for (int i = 0, ii = files.length; i < ii; i++) {
                System.out.println( files[i] + " match " + regex.matches(files));
    String[] pieces = regex.parts(files[i]);
    if (pieces != null)
    System.out.println(" path : " + pieces[0] + " file : " + pieces[1] + " ext : " + pieces[2]);
    I will leave it to you as an excercise to add support for spaces in path names, different separator characters, etc..

  • Help in Regular expression

    Hello..
    I wanted to write a regular expression to match the foll string..
    <!--endclickprintexclude--><!--startclickprintexclude--> <!--endclickprintexclude-->
    <p> <b>NEW ORLEANS, Louisiana (CNN) </b>
    -- Two years after Hurricane Katrina devastated coastal areas of Louisiana and Mississippi, residents say much of America has forgotten their plight.
    </p> <!--startclickprintexclude-->
    I tried doing..
    Matcher matcher= Pattern.compile("<!--endclickprintexclude--> <p><b>([^<^>]+?)</p><!--startclickprintexclude-->", Pattern.CASE_INSENSITIVE).matcher(story);
    Its not working...
    is there any other soln?

    Theres probably a better way to do this but here's a way that works.
    import java.util.regex.*;
    public class RegexTester{
    public static void main(String[] args){
         String text =
         "<!--endclickprintexclude--><!--startclickprintexclude--> <!--endclickprintexclude-->" +
         "<p> <b>NEW ORLEANS, Louisiana (CNN) </b>" +
         "-- Two years after Hurricane Katrina devastated coastal areas of Louisiana and Mississippi," +
         "residents say much of America has forgotten their plight." +
         "</p> <!--startclickprintexclude-->";
         String regex = ">((?:\\s*[\\S&&[^<>]]+\\s*)*?)<";
         Pattern p = Pattern.compile(regex);
         Matcher m = p.matcher(text);
         while(m.find()){
         System.out.println("Match: '" + m.group(1) + "'");
    }

Maybe you are looking for

  • Java 1.4 and AES Algorithm PLEASE HELP!!

    I hope this question has not already been asked. I have spent a long time searching the archives and documentation. I am attempting to migrate from jsdk1.3 to jsdk1.4 but have come up against the following problem. I need to create keys and encrypt f

  • Dynamic Name for CSV files

    I would like to be able to set a target CSV file who's name changes dynamically.  Specifically, it would be something like "today's date" + loan_Transactions (02-01-2008loan_Transactions for instance).  Any thoughts would be appreciated!!  Not having

  • JMS - Message Loss

    Hi All, I am trying to read message from SUN - JMS Queue to XI After reading the message XI is trying to persist the message to Database and here I am getting a SQL Exception That The JMS Message ID is of 71 characters where as the host field in XI D

  • Lightroom CC will not start on my mac?

    lightroom CC will not start on my mac?

  • How to reinstall Photoshop Elements without the CD

    Is this program and all my pictures lost Message title was edited by: Brett N