Regular Expression Escaped Digit "\d" Illegal Escape Character

Hello,
I'm trying to write a regular expression to determine if a String matches a date format that is defined as YYYYMMDD. For example, March 11, 2009 would be "20090311"
For the time being I don't care if an invalid month or day is entered. I've attempted both of the following
if (date.matches("(19|20)\d{4}")) {
  // warn the user
}and
if (java.util.regex.Pattern.matches("(19|20)\d{4}"), date)) {
  // warn the user
}And both yield Illegal Escape Character compilation errors, for the "\d" part of the regular expression.
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html#sum
Says that "\d" is the predefined digit character class. So at this point, I don't know what I'm doing wrong. I realize I could just define the character class myself, and use a pattern like "(19|20)[0-9]{4}", but I would like to know why "\d" isn't being recognized by the compiler.
Thanks,
Paul

paulwooten wrote:
Can someone give me an explanation of heuristics, as they might apply to SimpleDateFormat? Does this mean that if the format was similar the parser might figure it out? Say, if instead of "yyyyMMdd", it was "yyyyddMM", or "yyMMdd"?No. Since all of these are valid formats, there's no way for the parser to distinguish this.
Or does this have to do with rejecting February 29, and other dates like that.That's the one. When setLenient(false) is called, then the 29th February is only accepted in leap years.
It will also reject the 57th January when lenient is set to false (try parsing that with lenient=true, you'll be surprised).
I've read some of the wikipedia article about heuristics, but I'm confused as to how it would apply to this example.Don't concentrate to much on the term heuristics. Just remember: lenient=true means that not-really-correct dates will be accepted, lenient=false means more strict checks.

Similar Messages

  • Regular expression - escape characters

    Hi. Is there an escape character for "?", "[", "]", "{", "}" for regular expression? I tried to do the following: "[^[]?{}]*" (the string cannot contain a question mark, left or right bracket, or left or right curly brace). However, I get an error stating unexpected character.
    thanks,
    Paul.

    Hi. Is there an escape character for "?", "[", "]",
    "{", "}" for regular expression? I tried to do the
    following: "[^[]?{}]*" (the string cannot contain a
    question mark, left or right bracket, or left or right
    curly brace). However, I get an error stating
    unexpected character.
    You should only have to escape the characters that cause a problem in the character class, rather than everything so the following should work.
    "[^\\[\\]?{}]*"

  • Regular Expression escaping problem!

    Hi all,
    Well as you know characters such as '*' and '?' are reserved characters in regular expression so I suppose if I want to find the exact character (a '?' for example) in a string, I have to escape it with a backslash:
    str=str.replaceAll("\?","a");
    In the statement above, I need to replace all question marks with another character but it has a compile error:
    Error(116,48): invalid escape character
    to my surprise this following code does the job while it should be interpreted as: one occurance of the '\' character or nothing at all:
    str=str.replaceAll("\\?","a");
    What's the problem? what's the general rule on escaping such characters?

    I think you're right.
    The point is that java first interprets the String and handle its own scape characters then the result would be passed on to reqular expression parser.
    so I guess in order to search for one occurance of the '\' character or nothing at all the java string would be:
    so that the input to reqular expression parser would be:
    while in the first situation:
    a "\\?" java string is first trasformed into \? which will be considerd as one occurance '?' in reqular expression point of view...
    Message was edited by:
    nerssi
    Message was edited by:
    nerssi

  • Java regular expression: escaping {, [

    Hi, i would like to replace exactly the string "{s}", i tried the following
    myString.replaceAll("{s}","replaced");but it wont work and generated a runtime exception "illegal repetition", because { and } are not excaped. i then try to escape the chars using backslash as such
    myString.replaceAll("\{s\}","replaced");but it wont compile at all and saying: "illegal escape character in string literal".
    what should i do to fix this please? thanks!

    myString.replaceAll("\\{s\\}","replaced");

  • String.split() regular expression

    Regular expression escapes me. I have a line of a CSV file that looks like this:
    1,,3,2,45.00,"This & That, LLC",0
    I want the string split by commas but the problem with the line above is there's a comma in the name of the company...I obviously don't want the company name split in half...what would the regular expression be that I would provide to the split method to ensure that only commas not found in between double quotes are used to split the string into an array of Strings? is this possible?
    Thanks in advance!
    Rob

    Telling someone to google might be deserved, but it is mean and unhelpful.
    If you want to find a regex for CSV's see O'Reilly's "Mastering Regular Expressions" Section 8.4.4.3. Either buy the book - it's worth it - or subscribe to safari.

  • Fun fun regular expressions

    My goal: to create a regular expression that will match a four character hexadecimal value that is left-padded with spaces.
    Examples:"   1", "  A4", " 51C", "FFAB"All the alpha characters will be uppercase.
    My solution:"[0-9A-F]{4}| [0-9A-F]{3}|  [0-9A-F]{2}|   [0-9A-F]"My question is:
    Is there a more concise way to represent this? I am parsing a line of text that is formatted into columns and delimited with spaces, so this is actually a subexpression in a capturing group and the spaces are important.
    Thank you for any help you can provide.

    It's not easy, taken out of context, had to put the two delimiting spaces in to get a grip.
    I can make an alternative regex, but it is not "better" as such.
    Sorry for using perl, but when people talk regex ...#!/bin/perl/bin/perl.exe
    use strict;
    $^W = 1;
    $\ = "\n";
    my (@good) = ( "   1", "  AB", " 123", "cafe", );
    my (@bad) = ("123 ", "    ", "123", "12345", "gggg", "   123", " ", "",
                   "a a ", " a a", "1  1", );
    my $s;
    for $s (@good) {
         ismatch($s);
    for $s (@bad) {
         ismatch($s);
    sub ismatch {
         $_ = ' '.$_[0].' ';
         # if (/^ ([\dA-Fa-f]{4}| [\dA-Fa-f]{3}|  [\dA-Fa-f]{2}|   [\dA-Fa-f]) $/) {
         if (/^ (?! *[\d\w]+ +[\d\w])[ \dA-Fa-f]{4}(?<! ) $/) {
              print "Match: \"$_\"";
         else {
              print "No match: \"$_\"";
    }

  • [DW CC] Regular Expression and Back Reference in "Replace with": Escape

    I have a problem with escaping a character in "Replace with".
    Let's assume the following situation:
    Content:
    foobar
    Search for:
    (foo)(bar)
    Replace by:
    $1zot$2
    Result:
    foozotbar
    Everything is fine.
    But I want to insert the number "2" in between foo and bar.
    When I use
    Replace by: $12$2
    The result is:
    $12$2
    It seems that the regex engine interpretes the "$12" as a whole. And because there's no back reference with the count "12" DW cannot work correctly.
    The question:
    How can I "escape" the "2"?
    Thanks.

    Dreamweaver uses JavaScript for its Find and Replace with regex.
    I've just checked the Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan (O'Reilly). It deals with exactly this sort of situation where capturing groups can be ambiguous. This is what it says:
    "Java and JavaScript try to be clever with $10 [and above]. If a capturing group with the two-digit number exists in your regular expresssion, both digits are used for the capturing group. If fewer capturing groups exist, only the first digit is used to reference the group, leaving the second as a literal. Thus $23 is the 23rd capturing group, if it exists. Otherwise, it is the second capturing group followed by a literal 3."
    In other words, there is no way to escape the 2 in the Replace field. It would appear there's a bug in Dreamweaver's use of capturing groups.

  • Regular expression substitution with escaped $

    I'm looking to perform a substitution (along the lines of String.replaceAll()) that matches with the character $. I have tried $, \$, \\$, and variations thereof in the regex string utilizing String.replaceAll() and with a Pattern.compile(). In both cases I get an "Illegal repetition near index X" error. Anyone have suggestions as to escaping the $ character for regular expression substitutions?
    Edited by: dolcraith57 on Dec 6, 2007 11:18 AM

    It would help if you'd post details--e.g. original string and desired result, with an explanation of the rules.
    str1 = "a$1$2$b$";
    str2 = str1.replaceAll("\\$", "X"); // aX1X2XbX
    str3 = str1.replaceAll("\\d", "\\$"); // a$$$$$b$

  • Regular expression needed to escape dots

    Hello
    In a file , I might have several times a line like this :
    VALOR DESCUENTO .......                           1,505,728.80What is the regular expression to get *1,505,728.80* ? Please note that there are dots ..how do i escape them ?
    This is what I use , but it does not work
    String descuentoPattern = "VALOR DESCUENTO(?:\\s+?)(?:^\\s+?)(?:\\s+?)(.*)"; cheers,
    deibys

    BigDaddyLoveHandles wrote:
    The same way you escape any character -- with a backslash.Remembering to double-up backslashes in Java strings, of course.
    @deibys, your regex is wrong. Try this instead:
    String foo = "VALOR DESCUENTO .......                           1,505,728.80";
    String pattern = "VALOR DESCUENTO\\s*\\.+\\s+(.*)";
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(foo);
    if (m.matches()) {
         System.out.println("Match found: " + m.group(1));
    }

  • Illegal escape character

    Hi i am writing a servlet which has html in it too...so the commands for html pages i just use out.println("").
    But i wanted to add a new picture on the page and had this command
    out.println("<IMG SRC=C:\Documents and Settings\bsharma\My Documents\My Pictures\index1.gif>");
    but i get a compiling error saying 'illegal escape character'
    I know it is because of the \ ..but is there a way around it?
    -bhaarat

    Try:
    out.println("<IMG SRC=C:\\Documents and Settings\\bsharma\\My Documents\\My Pictures\\index1.gif>");

  • HTML Escaping Regular Expression

    Assume I have the following string:
    <font face="arial">this</font> is a <b>very nice</b> " <a href>String</a>Now say I want to allow everything above, except I want to escape certain tags... IE I want to allow:
    <b>,</b>,<font ...>,</font> and nothing else. The escaped string above should then be converted to:
    <font face="arial">this</font> is a <b>very nice</b> " & lt;a href & gt; String & lt;/a& gt;The idea I'm trying to implement is to allow form input that may contain limited html tags, that I define, and escape anything else.
    This seems like it would be an existing regular expression, does anyone have any ideas?
    Thanks!

    Kudos and thanks for the regex. I did not know how to do negation in a regular expression, ie (?!FONT|B)To answer an earlier post, the application works much like a message board. I accept input from a textarea, then write that input out as an html file (much like how this forum works). I'd like to accept certain HTML markup in the input, but disallow tags like "<javascript>", "<object>" and "<embed>", etc, as writing those tags would allow users to post malicious input (redirects, popups, etc). Thus, defining and parsing what tags I will accept is easier than defining the tags not to accept (and safer).
    That being said, escaping quotes is somewhat important, as " in html that is not in a tag should really be the converted to & quot; for w3c browser standards. However, with 95% of my original question answered (that being the most important part), I'm satisfied with this. Thanks to all for the help thus far!

  • Generating JavaDoc returns with "illegal escape character"

    Hello,
    I'm using JDeveloper 10.1.2.0.0.
    I'm trying to generate JavaDoc for a couple of my packages.
    The generator returns 2 errors due to "illegal escape character".
    This is the error message :
    C:\MyDocs\General Procs\Start_Java_Package\Portlets\src\PortletsUtils\Utils.java:65: illegal escape character
    + ".replace(/\à/g,\"a_accent\")"
    ^
    C:\MyDocs\General Procs\Start_Java_Package\Portlets\src\PortletsUtils\Utils.java:66: illegal escape character
    + ".replace(/\ç/g,\"c_cedile\")"
    ^
    The error is on the "à" and "ç".
    This special character is within a double quote, so it should be text for him.
    Compiling the package is no problem.
    What can I do so the generation of my javadoc continues ?
    Thanks a lot.
    Filip Huysmans.

    Because you don't escape the "\".
    String mypattern = "(<img\\w*)";

  • Regular Expression Character Occurance.

    Hello,
    I have a name textfield and I want certain characters like "-" to occur one time only.
    i.e. The textfield can accept "Jean Luc" or "Jean-Luc" (french name), but not "Jean--Luc" or "Jean------------Luc" right.
    The regular expression  /\-?/ looks correct but it does not seem to work.
    We use "\" because "-" is an escape character and the character "?" to make "-" occur 0  or 1 time only.

    I am making sure that the textfield accept only text like "Jean-Luc" and not "-----Jean--Luc".
    My regular expression is already very long so I will add 5 or more additional parameters in the if statement which will not be a problem.
    Below is a very common regular expression which looks simple but it will not accept "[email protected]" and non western characters.
    /^[a-zA-Z0-9._-]+@[a-zA-z0-9.-]+\.[a-zA-z]{2,4}$/
    Email regular expressions are complicated. The range of permissible email adresses and some domain sometimes include non western characters which is quite rare but certainly does exist. I guess there is no precise regular expression for user forms.
    Checking user input becomes more complicated if some bored to death folks have a habit of playing drums on keyboard which result to "asdf;lkjasdf;lkjasdf;lkajsdf;lkajsdf;lkajsdf;lkj".

  • Writing Regular Expression with a character ^, too difficult

    I want to change "^1Mandrake ^3Style ^4DM" this sentence to "Mandrake Style DM".
    (^ with number means color code)
    So..I used String.replaceAll() method with regular expression.
    But however hard I try, I cant find any solution for this.
    In php I could use \^ as a ^ character, but java dosnt support \^.
    How can I solve this problem?

    Use \\^ in your regex (you have to escape the slash, too).

  • What is the escape character for DOT in java regex?

    How to specify a dot character in a java regex?
    . itself represents any character
    \. is an illegal escape character

    The regex engine needs to see \. but if you're putting it into a String literal in a .java file, you need to make it \\., as Rene said. This is because the compiler also uses \ as an escape character, so it will take the first \ as escaping the second one, and remove it, and the string that gets passed onto the regex will be \.

Maybe you are looking for

  • Windows 7 (32) will not see iPhone 4S

    Right, there are loads of questions about just this issue on this and other forums and I've yet to see it answered, so I hope that we can finally sort it. I'm trying to use my iPhone 4S with a Windows 7 32-bit PC. In device manager, one can clearly s

  • How can I get iTunes to transfer only the HD version???

    Hello, Is there a way I can set iTunes to transfer only the HD version of a video to AppleTV, and not include the SD version, while keeping both versions in the iTunes library? Currently, both versions are being transferred when I sync. Regards.

  • Full outer join Bug or my misunderstanding?

    CREATE GLOBAL TEMPORARY TABLE BP_ATTRIBUTE_CHARVAL_GTT    (     "ATTRIBUTE_ID" NUMBER(10,0),      "PARTNER_ID" NUMBER(10,0),      "CHAR_VALUE" VARCHAR2(4000 BYTE),      "LAST_UPDATE_DATE" DATE,      "DISABLE_DATE" DATE    ) ON COMMIT DEETE ROWS ; CRE

  • Running Crystal Reports in background mode

    Ist there any way to run Crystal Reports against R/3 (ECC) in background mode instead of as a dialog user? We're having timeout issues since the dialog timeout is set to 30 minutes. We have several reports that run quite a bit longer than that. Updat

  • Erasing a config and vlan.dat file in Catalyst 4507R Switch

    Hi, I am unable to erase the configuration from Catalyst 4507R Switch.When i do "write erase" and reload the switch,the configuration still remains on the switch. Switch1#write erase Erasing the nvram filesystem will remove all configuration files! C