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$

Similar Messages

  • 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));
    }

  • Regular expression evaluation with logical operator

    Hi All,
    I am bit confuse with expression evaluation with logical operator. I am trying to understand below expression.
    eXa.getTrue() && eXa.getFalse() || eXa.getFalse() && eXa.getTrue() || eXa.getFalse() comes as false and True Count: 1 False Count: 3
    As per understanding it should be true with True Count: 1 False Count: 3
    it should execute 1st getTrue() and then 1stGetFalse() and then 2nd getfalse() and should skip 2nd getTrue() and execute 3rd fetFalse()
    eXa.getTrue() && eXa.getTrue() || eXa.getFalse() && eXa.getTrue() || eXa.getFalse() comes as true and True Count: 2 False Count: 0
    As per understanding it should be true with True Count: 3 False Count: 0
    it should execute 1st 2 getTrue() and skip 1st getFalse() and then execute 3rd getTrue() and skip last getFalse().
    eXa.getTrue() || eXa.getFalse() && eXa.getFalse() || eXa.getTrue() && eXa.getFalse() comes as true and True Count: 1 False Count: 0
    As per understanding it should be true with True Count: 2 False Count: 2
    it should execute 1st getTrue() and skip 1st getFalse() and then execute 2nd getFalse() and then execute 2nd getTrue() and then 3rd getFalse()
    Please help me to understand above expressions.
    Here is the methods definition:
    private boolean getTrue() {
              trueCount++;
              boolean retrunValue = 4 > 3;
              return retrunValue;
    private boolean getFalse() {
              falseCount++;
              boolean retrunValue = 3 > 4;
              return retrunValue;
    Thanks for ur help

    >
    adding parenthesis to make order of ops more obvious. adding "?" to show un-executed calls.
    (eXa.getTrue() && eXa.getFalse()) || (eXa.getFalse() && eXa.getTrue()) || eXa.getFalse()  comes as false and True Count: 1 False Count: 3
    (T && F) = F
    (F && ?) = F
    (F) = F
    F || F || F = F
    (eXa.getTrue() && eXa.getTrue()) || (eXa.getFalse() && eXa.getTrue()) || eXa.getFalse()  comes as true and True Count: 2 False Count: 0
    (T && T) = T
    (? && ?) = ?
    (?) = ?
    T || ? || ? = T
    eXa.getTrue() || (eXa.getFalse() && eXa.getFalse()) || (eXa.getTrue() && eXa.getFalse())  comes as true and True Count: 1 False Count: 0
    (T) = T
    (? && ?) = ?
    (? && ?) = ?
    T || ? || ? = T

  • Regular expression breaks with \00 in input string

    I wrote the following code to illustrate the problem.
    Clearly the match should occur in both cases, but it does not occur if \00 is in the input string (within the < > ).
    I am not even searching for \00 or \01. This makes the regular expression match rather useless if you have text that contains data in hex form. I am using Labview 8.2. Is this a known bug? Is there a work around?
    Tammo
    Message Edited by Tammo on 03-06-2008 12:26 PM
    Message Edited by Tammo on 03-06-2008 12:26 PM
    Attachments:
    RegEx1.vi ‏56 KB
    BlockDiagram1.jpg ‏18 KB
    FrontPanel1.jpg ‏18 KB

    There was a brief discussion on this not too long ago.

  • Regular Expressions problem with OPA

    hi,
    I have version OPA 10.2, when I try using regualr expressions it won't let you submit data and move onto the next screen.
    I've tried for example using the OPA hel's National Insurance number, I tried for a 6 digit number using:
    For a minimum of 6 digits:
    ^\D*(?:\d\D*){6,}$
    and I also tried:
    ^[0-9]{1,6}$
    None of them worked; is there something obvious I'm missing?
    Thanks

    Hello,
    Just tried this out and the two expressions worked as I would expect. I receive the error message as configured in the properties file and cannot progress to the next screen until I enter 6 digits or more. Is that different to the behaviour you are seeing? Also, have you tried using the debugger without screens? The error message would appear at the top of the debug window "Cannot set value of attribute 'test'. Reason: Invalid Value."
    Also, are you trying to validate a text attribute or a number attribute? Number attributes can be a little trickier since the regex appears to run against them after they're converted. So if the user enters "99", the regex validates against "99.0".

  • Extract values with Regular Expression

    How to extract values into [ ] using regular expression.
    With data As
    Select 'AAAAAA[10] AAA: 19C' Txt From Dual Union all
    Select 'XX[450]-10A' Txt From Dual Union all
    Select '[5]AVC19C' Txt From Dual Union all
    Select 'FVD[120]D2AC' Txt From Dual
    )I hope this return
    10
    450
    5
    120Thanks in advanced

    user11118871 wrote:
    Thanks for all.
    Hi BluShadow, can you explain what this is doing!?
    ThanksSure.
    Search for ----------------|           /------- Replace the found pattern in the search string with backreference 1
                         /------------\   /\       (the first thing backreferenced in the search string)
    regexp_replace(txt, '^.*\[(.*)\].*$','\1')
                         |\/\/\--/\/\/|
                         | \ \  /  \ \|
                         | | |  |  | |\- End of string
                         | | |  |  | |
                         | | |  |  | \- Any number of characters
                         | | |  |  |
                         | | |  |  \- Right square bracket (escaped)
                         | | |  |
                         | | |  \- any characters (backreferenced by round brackets)
                         | | |
                         | | \- Left square bracket (escaped)
                         | |
                         | \- Any number of characters
                         |
                         \- Start of stringEdited by: BluShadow on Jun 29, 2009 2:19 PM

  • Regular expressions: serious design flaw?

    I wondered why sometimes, the replaceAll() method works in my code and sometimes it throws a java.util.regex.PatternSyntaxException. I wrote a little test case to show the problem
    private void regularExpressionTest() {
            String escapers = "\\([{^$|)?*+."; //characters to escape to avoid PatternSyntaxException
            String text = "The quick brown fox jumps over the lazy dog.";
            System.out.println("Original: "+text);
            String regExp = "o";
            String word = "HELLO";
            String result = text.replaceAll(regExp, word);
            System.out.println("Replace all '"+regExp+"' with "+word+": "+result);
            text = "The quick brown {animal} jumps over the lazy dog.";
            System.out.println("Original: "+text);
            regExp = "{animal}";
    //        regExp = escapeChars(regExp, escapers); //escape possible regular expression characters
            word = "catterpillar";
            result = text.replaceAll(regExp, word);
            System.out.println("Replace all '"+regExp+"' with "+word+": "+result);
    }//regularExpressionTest()The output is:
    Original: The quick brown fox jumps over the lazy dog.
    Replace all 'o' with HELLO: The quick brHELLOwn fHELLOx jumps HELLOver the lazy dHELLOg.
    Original: The quick brown {animal} jumps over the lazy dog.
    java.util.regex.PatternSyntaxException: Illegal repetition
    {animal}
         at java.util.regex.Pattern.error(Pattern.java:1528)
         at java.util.regex.Pattern.closure(Pattern.java:2545)
         at java.util.regex.Pattern.sequence(Pattern.java:1656)
         at java.util.regex.Pattern.expr(Pattern.java:1545)
         at java.util.regex.Pattern.compile(Pattern.java:1279)
         at java.util.regex.Pattern.<init>(Pattern.java:1035)
         at java.util.regex.Pattern.compile(Pattern.java:779)
         at java.lang.String.replaceAll(String.java:1663)
         at de.icomps.prototypes.Test.regularExpressionTest(Test.java:57)
         at de.icomps.prototypes.Test.main(Test.java:34)
    Exception in thread "main" As the first replacement works as espected, the second throws an Exception. Possible because '{' is a special character for the regular expression API. In case I know the regular expression, i could escape these special characters. But in my generic server app, the strings are all parameters, so the only way for replaceAll() to work is, to escape all possible special characters in the regular expression.
    1. Is there a complete list of all special characters for regular expressions that need to be escaped?
    2. Is there a similar replaceAll() method without regular expressions? So that all occurences of a substring can be replaced by another string? (So far, I wrote my own method but this is of course more time consuming for massive string operations.)

    1. The complete list of specially-recognized characters are listed in the Java 1.4.* API. (Of course, new ones may eventually be added as the regex package matures).
    2. It is time consuming to program in general. You should have written your own utility method that goes through a String using indexOf and building up the String in a StringBuffer, and apparently you did. Now you have the utility method...you no longer need to write that method again.
    3. Or you could have written some kind of method that automatically escapes the specially-recognized characters...

  • Regular expressions in 10g

    Can any body provide good Oracle 10g regular expression tutorial with example link ?

    Here below links from nice post entries from cd :
    Introduction to regular expressions ...
    Introduction to regular expressions ... continued.
    Nicolas.

  • Java – Regular Expressions – Finding any non digit byte in a multiple byte

    Hello,
    I’m new to JAVA and Regular Expressions; I’m trying to write a regular expression that will find any records that contain a non digit byte in a multiple byte field.
    I thought the following was the correct expression but it is only finding records that contain “all” non digit bytes.
    \D{1,}
    \D = Non Digit
    {1,} = at least 1 or more
    Below is my sample data. I would like the regular expression to find all of the records that are not all numeric. However when I use the regular expression \D{1,} it is only finding the 2 records that all bytes are non digits. (i.e. “ “ and “A “)
    “ 111229”
    “2 111229”
    “20091229”
    “200912c9”
    “201#1229”
    “20101229”
    “20110229”
    “20111*29”
    “20111029”
    “20111229”
    “20B11229”
    “A “
    “A0111229”
    Please note I have also tried \D{1,}+ and \D{1,}? And they also do not return my desired results
    Any assistance someone can provide would be greatly appreciated.

    You don't show the code you are using but I surmise you are using String.matches() which requires that the whole target must match the regular expression not just part of it. Instead you should create a Pattern and then a Matcher and use the Matcher.find() method. Check the Javadoc for Pattern and Matcher and look at the Java regex tutorial - http://docs.oracle.com/javase/tutorial/essential/regex/ .
    P.S. You can re-use the Pattern object - you don't have to create it every time you need one.
    P.P.S. Java regular expressions work with characters not bytes and characters are not not not bytes.

  • Regular expression in oracle for hypen

    Hi,
    I want to match a word "{color:#993300}83-ASG{color}" using regexp_like and i used '{color:#993300}^83-*{color}' pattern to match this word but this also matches words like "{color:#993300}8307-YUF{color}". could anyone please tell me what pattern should i use to match words like {color:#993300}83-ASG{color}.
    Also i need to know the similar pattern in oracle for the "{color:#993300}\b{}{color}" used in .net.
    Thanks in advance.
    Prasad

    Hi Prasad,
    Your regex could be as simple as '^83-'
    So, not much use for a regular expression:
    SQL> with test_data as (select '83-ASG' txt from dual union all
                       select '8307-YUF' from dual)
    -- end of test data
    select txt from test_data
    where txt like '83-%'
    TXT    
    83-ASG 
    1 row selected.Unless, you add some more value to it, perhaps like
    SQL> with test_data as (select '83-ASG' txt from dual union all
                       select '8307-YUF' from dual)
    -- end of test data
    select txt from test_data
    where regexp_like(txt, '^83-[[:upper:]]{3}$')
    TXT    
    83-ASG 
    1 row selected.Regards
    Peter

  • Regulare Expressions - Uses of logical operators

    I need to make use of logical operators within a regulare expression. (greater than, equal, etc.)
    It seems to me that java.util.regex.Pattern does not support that kind of expression. First of all: Is this true (If I am wrong with my assumption, how would the expression look like). Secondly: Which library does support this expression?
    Thanks in advance!

    Regular expressions deal with characters. In that context all characters are 'equal'. You better explain your question a helluva lot better than that.

  • Search  application that can handle regular expressions

    I am desperately seeking for my PhD an OSX 10.6 application that can search through all my data. That application need to have *efficient search algorithms* for complex pattern searching.
    For example I want to search all my documents having the word cancer inside the file.
    Not only search for the filename cancer BUT search inside the documents with all the extensions (pdf, rtf, doc, etc.)
    In Windows I use +Filelocator Pro+.
    Is there a Mac OSX application like +Filelocator Pro+ for search?
    An application that can handle regular expression support, with any of the following options:
    +Export results to Text, command line options, Network drive searching, Boolean searches (e.g. AND, OR, and NOT), Perl compatible regexp option, Built in file viewer, Word, Excel and PDF searching, Open Office, Word Perfect option using IFilters, Unicode support, support for: ZIP, RAR, CAB, 7-Zip, ARJ, Bzip, CHM, CPIO, DEB, DMG, GZIP, HFS, ISO, LZH, MSI, NSIS, RPM, TAR, UDF, WIM, XAR, Z formats, Active Scripting support, Export as Text, CSV, XML, HTML, or XSLT custom format, File attribute searching , Relative date/time searches, Repositionable contents pane, Search within search, Exclude folders list,+ etc

    You might try the freeware EasyFind. It allows boolean and wildcard searches. How many of the other features in your "wish list" it offers I haven't checked. If EasyFind doesn't offer sufficient power, take a look at FoxTrot Personal Search or FoxTrot Professional Search.
    And of course there's always grep which can be incredibly powerful once you learn all its ins and outs.
    Regards.

  • [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.

  • What's wrong with the regular expression?

    Hi all,
    For the life of me I can not figure out what is wrong with this regular expression
    .*\bA specific phrase\.\b.*
    This is just an example the actual phrase can be an specific phrase. My problem comes when the specific phrase ends in a period. I've escaped the period but it still gives me an error. The only time I don't get an error is when I take off the end boundry character which will not suffice as a solution. I need to be able to capture all the text before and after said phrase. If the phrase doesn't have a period it would look like this...
    .*\bA specific phrase\b.*
    which works fine. So what is it about the \.\b combination that is not matching?
    I've been banging my head on this for a while and I'm getting nowhere.
    The application highlights text that comes from a server. The user builds custom highlights that have some options. Highlight entire line, match partial word, and ignore case. The code that builds my pattern is here
    String strHighlight = _strHighlight;
            strHighlight = strHighlight.replaceAll("\\*", "\\\\*");
            strHighlight = strHighlight.replaceAll("\\.", "\\\\.");
            String strPattern = strHighlight;
            if(_bEntireParagraph)
                if(_bPartialWord)
                    strPattern = ".*" + strHighlight + ".*";
                else               
                    strPattern = ".*\\b" + strHighlight + "\\b.*";           
            else
                if(_bPartialWord)
                    strPattern = strHighlight;
                else               
                    strPattern = "\\b" + strHighlight + "\\b";  
            if(_bIgnoreCase)
                _patHighlight = Pattern.compile(strPattern, Pattern.CASE_INSENSITIVE);
            else
                _patHighlight = Pattern.compile(strPattern);So for example I matching the phrase: The dog ate the cat. And that phrase came over in the following text: Look there's a dog. The dog ate the cat. "Oh my!"
    And my user has the entire line and ignore case options selected then my regex woud look like this: .*\bThe dog ate the cat\b.*
    That should get highlighted, but for some reason it doesn't. Correct me if I'm wrong but doesn't the regex read as follows:
    any characters
    word boundry
    The dog ate the cat[period]
    word boundry
    any characters until newline.
    Any help will be much appreciated

    A word boundary (in the context of regexes) is a position that is either followed by a word character and not preceded by one (start of word) or preceded by a word character and not followed by one (end of word). A word character is defined as a letter, a digit, or an underscore. Since a period is not a word character, the only way the position following it could be a word boundary is if the next character is a letter, digit or underscore. But a sentence-ending period is always followed by whitespace, if anything, so it makes no sense to look for a word boundary there. I think, instead of \b, you should use negative lookarounds, like so:   strPattern = ".*(?<!\\w)" + strHighlight + "(?!\\w).*";

  • Help with java regular expressions

    Hi all ,
    i am going to match a patternstring against an input string and print the result here is my code:
         import java.util.regex.*;
         import java.util.*;
         public class Main {
              private static final String CASE_INSENSITIVE = null;
              public static void main(String[] args)
              CharSequence inputStr = "i have 5 years FMCG saLEs exp on java/j2ee and i worked on java and j2ee and 2 projects on telecom java j2ee domain with your  with saLEs maNAger experience of java j2ee and c# having very good  on c++ exposure in JAVA"
             String patternStr = "\"java j2ee\" and \"c#\"";
              StringTokenizer st = new StringTokenizer(patternStr,"\",OR");
             Matcher matcher=null;
              while(st.hasMoreTokens()){
                   String s=st.nextToken();
                   Pattern pattern = Pattern.compile(s,Pattern.CASE_INSENSITIVE);
               matcher = pattern.matcher(inputStr);
               while (matcher.find()) {
                  String result = matcher.group();
                 if(!result.equalsIgnoreCase(" "))
                             System.out.println("result:"+result);
         when i compile this code i am getting the expected result...ie
    result:java j2ee
    result:java j2ee
    result: and
    result: and
    result: and
    result: and
    result: and
    result: and
    result:c#
    but when i replace String patternStr = "\"java j2ee\" and \"c#\""; with
    String patternStr = "\"java j2ee\" and \"c++\""; i am just getting c in the result instead of c++ ie i am getting result :
    result:java j2ee
    result:java j2ee
    result: and
    result: and
    result: and
    result: and
    result: and
    result: and
    result:C
    result:c
    result:c
    result:c
    result:c
    result:c
    result:c
    In the last lines i should get result:c++ instead of result: c
    Any ideas please
    Thanks

    In the last lines i should get result:c++ instead of result: cThe regular expression parser considers the plus sign '+' a special
    character; it means: one or more times the previous regular expression.
    So 'c++' means one or more 'c's on or more times. Obviously you don't
    want that, you want a literal '+' plus sign. You can do that by prepending
    the '+' with a backslash '\'. Unfortunately, the javac compiler considers
    a backslash a special character and therefore you have to 'escape'
    the backslash also, by adding another backslash. The result looks
    like this:"c\\+\\+"kind regards,
    Jos

Maybe you are looking for