Regex replaceAll question

I am using replaceAll to replace a bunch of "tags" with content for this bit of software that I am porting (from something else) that creates documents (in the end) by populating templates with data.
Here's my problem. The "tags" are all okay (not giving any regex content) but some of the data is. Because at first now I hit data that as a String has some regex funky characters in it. And regex got all all whiny about that because there aren't any matching groups. Well no. That's true.
So I have to escape the $. But it occurs to me that I could well have more than this problem with other bits of content (including some parts I haven't gotten to yet) and I am wondering if there is any sort of easy solution. Is there way to tell replaceAll that the replacement String is a "literal" replacement i.e. I don't want any regex parsing at all just replace the found "tag" with the "content", that's it.
Some sort of escape the whole sequence? Possibly. But I don't understand what it would be. \ is just for as single character?
So any quick solution? Or alternative?
BTW I am stuck with 1.4 on this project.

yawmark wrote:
I'd recommend trying Apache Commons StringUtils.
Hope this message doesn't disappear into the aether.
~I think it did for awhile but like Lazarus arose...
Anyway thank you for the effort.
This is an interesting suggestion but I'd rather not go the route of adding more libraries.
What I did at first was
private void replaceAll(StringBuffer buff, String toFind, String toReplace){
  while(buff.indexOf(toFind)>-1){
     buff.replace(buff.indexOf(toFind),buff.indexOf(toFind)+toFind.length(),toReplace);
}which worked good enough for me but someone else pointed out quoteReplacement and just doing my own version of that. Which works well too.
Anyway thanks again I do appreciate it what with the current situation and all.

Similar Messages

  • Regex pattern question

    Hi,
    I'm trying to get my feet wet wtih java and regular expressions, done a lof of it in perl, but need some help with java.
    I have an xml file (also working through the sax tutorial, but this question is related to regex)that has multiple elements, each element has a title tag:
    <element lev1>10<title>element title</title>
    <element lev2>20<title>another element title</title>
    </element lev2>
    </element lev1>If I have the following pattern:
    Pattern Title = Pattern.compile("(?i)<title>([^<]*)</title>");that picks up the titles, but I can't distinguish which title belongs to which element. Basically what I want to have is:
    Pattern coreTitle = Pattern.compile("(?i)<element lev1>(**any thing that isn't an </title> tag**)</title>");looked through the tutorials, will keep looking, I'm sure it's in there somewhere, but if someone could point me in the right direction, that would be great.
    thanks,
    bp

    Just guessing, but maybe...
    Pattern.compile("(?i)<element lev1>*<title>([^<]*)</title>");
    But it seems that things like parsing with SAX (or loading to a DOM) or XPath would be much better suited to parsing out XML then regexp.

  • Quick regex "link" question

    I need to extract the link and the links anchor text from Strings which take the following format:
    Bestsellers
    Or
    Find Gift
    (I.e. has more attributes other than the "href" attribute)
    I have the following regex:
    <a\s+[^<>]*?href\s*=\s*["'](.*)["']\s*>(.*?)</a>
    However, although, this works fine for the first example above, it does not match the second example correctly. Instead the "link" it matches comes out as:
    /gp/product/" id="gift" name="findGift
    When it should be:
    gp/product/
    I thought my regex pattern says "extract the link (everything between) the two quotes after "href=" but it seems to match any other attributes which may be inside the "<a>" tag.
    Could someone explain where I have gone wrong.
    Thanks

    Watch out with those .* things. Try this one:
    &#60;a\s*href\s*=\s*['"]([^'"]*)[^>]*>([^&#60;]*)&#60;/a>

  • Simple REGEx Group Question...

    Hi,
    Can someone please explain something with RegEx's to me concerning groups?
    In the following code:
    Pattern p = Pattern.compile("([A-Z][a-z]+) ([a-z]+) .*");
    Matcher m = p.matcher("Aus bus L. 1771");
    if (m.matches()) {
         System.out.println("Groups:");
         for (int i=0; i<m.groupCount(); i++) {
              System.out.println("  " + i + ": " + m.group(i));
    }I expected group 1 to be "Aus" and there to be a group 2 of "bus".
    If I change the RegEx to
    Pattern p = Pattern.compile("([A-Z][a-z]+) (([a-z]+)) .*");Then I do get groups 0, 1 and 2.
    Why does it need the extra "(" and ")" at the last group.
    Thanks for any help!

    Oooops:
    for (int i=0; i<=m.groupCount(); i++) {Be the fix.... <= and not <

  • String replaceAll() question!

    Hello,
    i'm using the following to replace two characters from my input string
    String str; //some input string
    str = str.replaceAll("a", "bc");
    str = str.replaceAll("x", "yz");Is there a way to do this in single command (using String's replace() or
    replaceAll()... or something else)?
    Kind regards!

    tr = str.replaceAll("a", "bc").replaceAll("x","yz");If the OP needs something more sophisticated than this then he should look at
    http://elliotth.blogspot.com/2004/07/java-implementation-of-rubys-gsub.html

  • Regex related question

    m'kay
    i've got a problem, i need to create a regex to check if string S contains at least X patterns P
    i produced this code to test my regex's, you may use it as well to see if you're on right track...
    // works with JDK 1.4 or better
    public class RegexTest {
    public static void main(String[] args) {
      System.out.println(
       args[0]
       + (args[0].matches(args[1]) ? " matches " : " does not match ")
       + args[1]
    }any (GOOD) ideas how to do it?

    import java.util.regex.*;
    public class test3
       // searching for 3 or more of the pattern "aba"
       public static void main( String [] args )
          Pattern p = Pattern.compile( "(?:aba){3,}" );
          Matcher m = p.matcher( "helloabaabaaba" );
          if ( m.find() )
             System.out.println( "Found the match at index: " +
                         m.start() + "; the match is:" + m.group() );
    }

  • Regex Java Question.

    I'm trying to create a regex that will not match something. What I mean is if I have the string "this" I want everything but "this" to match the regex.
    "not this" == Match
    "something" == Match
    "this blah" == Match
    "this" == Not a Match
    "hist" == Match.
    I have come up with: ".*[^(this)].*" but, it doesn't work for "hist".
    Any Ideas?
    -- Steve

    Note that that regex will also match an empty string. If you want to require at least one character, add a bit:  Pattern.compile("^(?!this$).+");Or, to require at least one non-whitespace character:  Pattern.compile("^(?!this$)\\S.*");

  • Using RegEx in Subscription Criteria

    Using RegEx in Subscription Criteria
    Hello
    I want to use RegEx expression for filtering in my Subscription criteria, as follows:
    Let say all the monitor I created start with same set of characters i.e.
    "My Monitor"
    Therefore I have several monitors called
    My Monitor ABC
    My Monitor 123
    My Monitor XYZ
    Therefore as part of the Subscription Criteria, under "with a specific name" I currently have
    My Monitor%
    The % meaning any one or more characters. That works find I receive notifications for alerts from all of the monitors with the above names.
    Now what I want to do is keep this one subscription criteria but exclude notifications from say My Monitor 123. I still want to receive notifications from the other two monitors, therefore I was thinking this is a case for RegEx
    First question is can I use RegEx in the criteria "with a specific name" field? I guess I am already doing the with the % however, I believe that is an SQL expression rather than a true RegEx expression?
    The following blog has some detailed information
    http://social.technet.microsoft.com/Forums/en-US/operationsmanagergeneral/thread/ac0bf65f-f562-4f8c-b624-5fbe7ee2e795/
    I am not clear if this would work in my case, for example it states the ^ character is used to denote NOT. Based on this I was thinking about changing the above
    My Monitor%
    To
    My Monitor%[^123]
    Will the above work, is it the correct syntax?
    Any advise, most welcome
    Thanks you all
    Ernie

    Hello Yury,
    Thanks again for your help. Your solution worked, however with a slight difference as I discovered something else while testing.
    Basically the example above
    My Monitor [^1][^2][^3]%
    Only takes into account the First character of the word/phrase for example, using the above filer, the results were
    My Monitor ABC - pass
    My Monitor 123 - no pass
    My Monitor XYZ - pass
    My Monitor 222 - pass
    My Monitor XY3 - pass
    I therefore had to add an _ as part of the filter meaning one character, therefore using the above example if I want to block
    My Monitor 123
    My filter would be as follows
    My Monitor [^1][^_2][^__3]%
    i.e. 1 being the first character, 2 being the second character by placing any single character in front of it using the _ then 3 being the third character by placing and two characters
    in from of it by using two _ characters i.e. __
    Thanks again, I could not of figured it out without your help
    Ernie

  • How do I view multiple desktops/Spaces in a single screen?

    I'm used to viewing a large TV with multiple desktops simultaneously in an operating room. I'm wondering if it's possible to separate a TV I have connected to my early 2011 MacBook Pro into four separate desktops (e.g. dividing the TV into 4 quadrants)? I'm assuming there's no legitimate workup using OS X Yosemite but it'd be great to know if anyone has done this before. Thanks. 

    r9973 wrote:
    Sorry, more like: String test = "Some        Text       Here"Want to convert to String test = "Some Text Here"
    Post the code that you used to test the regex. I just tried it and it worked fine for me. All you need to do is apply the regex replaceall to your string variable that holds the string
    String test = "Some        Text       Here";
    test = test.replaceAll(" +", " ");
    System.out.println(test);And thats it.

  • Off Topic: Books about Regular Expression

    Hi
    Somebody can to indicate books about Regular Expression in Oracle ?
    Thanks

    Regex tag of Blog of Volder.
    http://volder-notes.blogspot.com/search/label/Regular%20Expressions
    This entry mentions my regex solution :-)
    http://volder-notes.blogspot.com/2007/10/removing-duplicate-elements-from-string.html
    By the way
    My regex homepage mentions regex problems of perl like regex (regex of EmEditor).
    http://www.geocities.jp/oraclesqlpuzzle/regex/
    example questions (written by Japanese language)
    http://www.geocities.jp/oraclesqlpuzzle/regex/regex-2-1.html
    http://www.geocities.jp/oraclesqlpuzzle/regex/regex-3-5.html
    http://www.geocities.jp/oraclesqlpuzzle/regex/regex-4-4.html

  • How do I replace multiple consecutive spaces with a single space?

    I need to convert any occurrence of multiple consecutive spaces in a string to a single space. How do I create the regex pattern to do that?

    r9973 wrote:
    Sorry, more like: String test = "Some        Text       Here"Want to convert to String test = "Some Text Here"
    Post the code that you used to test the regex. I just tried it and it worked fine for me. All you need to do is apply the regex replaceall to your string variable that holds the string
    String test = "Some        Text       Here";
    test = test.replaceAll(" +", " ");
    System.out.println(test);And thats it.

  • Using a local variable in regex portion of replaceAll(regex, replacement)

    While this works..
    output = output.replaceAll("(HED>|AUT>)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
    I'd like the list of alternation values to be contained in a variable, for example:
    String nodeLIst = "HED>|AUT>";
    output = output.replaceAll("(nodeList)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
    The extension of this would be so I can store this stuff in a db as a list and avoid compilation on change, but please don't let this muddy the waters... :)
    Any pointers are much appreciated. Links to specific reading material, etc. I've scoured Friedl's Mastering Regular Expressions to no avail. This approach is supported by some other regex engines I've used (perl, php, ORO?) but I'm new to Java.
    TIA,
    Mark

    I've scoured Friedl's Mastering Regular Expressions to no avail.Did you look on page 209? In the book, that code sample is labelled "Building Up a Regex Through Variables in Java". That should have been a clue. ^_^
    But seriously, you're probably thinking of the interpolated strings you find in scripting languages like Perl, PHP, Ruby, etc.. But that's a feature of the language itself, not the regex engine, and Java doesn't work that way. (The $1, $2, etc., in the replacement string are processed by the Matcher class, in a very limited imitation of Perl's variable interpolation).
    However, you can fake it pretty well with String's format() method:   String regex = String.format("(%s)(.*)(</\\1)", theAlternation);
      output = output.replaceAll(regex, "$1<![CDATA[$2]]>$3"); That way, you can easily escape the dynamic part, in case it might contain regex metacharacters:   String regex = String.format("(%s)(.*)(</\\1)", Pattern.quote(theAlternation));

  • Regex question

    Hi,
    I have a question regarding the regular expressions in java.
    Let's say I have the following regex: "(one)|(two)|(three)" and the following string: "two". The string obviously matches the regex, because of the "\2" group. Is there any way to determine the group number that matched the string, without having to use something like:
    for (int i = 1; i <= matcher.groupCount(); i++)
    }

    It's not top secret, the time difference is the problem.
    It's for a school project. We have to make Pascal Compiler and the first step is the Lexical Analyzer. This means that I have some regular expressions for identifiers, numeric constants, string constants and so on...
    For example the regex for the identifiers (variable name) looks like: "[a-zA-Z_][a-zA-Z0-9_]*", but the one for the key words is basically an array, like the one in my first post.
    The regular expressions work fine, but for the next part of the project I need to know the index of the key words, within the key word array (which in my case is a regular expression). So this is why I was wondering if there is any way to get the group number, without having to iterate through the whole regex.

  • Regex question: replace

    Hi,
    I'm getting into java.util.regex lately. Having used Perl for regex I'm trying to get familiar with Java's regex "spirit".
    Concerning replacement we can use replaceAll or replaceFirst however:
    - what if I want to replace only the third or fourth element?
    - what if I want to replace second to fourth element?
    in PERL we use " regex_epression_here for 2..4;" for instance.
    I you would have some interesting website/tutorials related to JAVA regex that would be great.
    Thanks for your help.
    Rgds,
    SR

    Yep,
    here is a sample of replacement in Perl
    $Line =~ s/\]/|/ for 2..4; #Replace 2nd 'til
    4th delimiter (]) with pipe (|)
    ....Based on the reference I gave earlier
    import java.util.regex.*;
    * A rewriter does a global substitution in the strings passed to its
    * 'rewrite' method. It uses the pattern supplied to its constructor,
    * and is like 'String.replaceAll' except for the fact that its
    * replacement strings are generated by invoking a method you write,
    * rather than from another string.
    * This class is supposed to be equivalent to Ruby's 'gsub' when given
    * a block. This is the nicest syntax I've managed to come up with in
    * Java so far. It's not too bad, and might actually be preferable if
    * you want to do the same rewriting to a number of strings in the same
    * method or class.
    * See the example 'main' for a sample of how to use this class.
    * @author Elliott Hughes
    public abstract class Rewriter_1
        private Pattern pattern;
        private Matcher matcher;
         * Constructs a rewriter using the given regular expression;
         * the syntax is the same as for 'Pattern.compile'.
        public Rewriter_1(String regularExpression)
            this.pattern = Pattern.compile(regularExpression);
         * Returns the input subsequence captured by the given group
         * during the previous match operation.
        public String group(int i)
            return matcher.group(i);
         * Overridden to compute a replacement for each match. Use
         * the method 'group' to access the captured groups.
        public abstract String replacement(int index);
         * Returns the result of rewriting 'original' by invoking
         * the method 'replacement' for each match of the regular
         * expression supplied to the constructor.
        public String rewrite(CharSequence original)
            this.matcher = pattern.matcher(original);
            StringBuffer result = new StringBuffer(original.length());
            int index = 0;
            while (matcher.find())
                matcher.appendReplacement(result, replacement(++index));
            matcher.appendTail(result);
            return result.toString();
        public static void main(String[] arguments)
            String result = new Rewriter_1("\\|")
                public String replacement(int index)
                    if ((index >= 3) && (index <=5))
                        return "y";
                    else
                        return group(0);
            }.rewrite("| | | | | |");
            System.out.println(result);
    }

  • Regex in String.replaceall()

    I wanted to remove ewg text from following lines completely.
    ewg#First line
    ewg#Second line
    ewgThird line
    For this i have used String class replace all method as follows:
    StringBuffer sb = new StringBuffer(returnString.replaceAll("(?i)\\bentfw\\b",""));The problem is this code is replacing only first two lines not the third line. Please help me

    returnString.replaceFirst("(?i)^ewg","")i tried this but its not removing ewg at allSeems to work just fine for me:
    String[] lines = new String[]{"ewg#First line",
    "ewg#Second line", "ewgThird line", "a line not
    starting with ewg"};
    String regex = "(?i)^ewg";
    for (String line : lines) {
         System.out.println(line.replaceFirst(regex, ""));
    sorry for long delay reply.
    i still couldnt solve this problem.
    i am not using any string array but a single string that separates these three lines with \n

Maybe you are looking for

  • ATP Quantity - not to be reduced by an outbound delivery

    Hi, We have the following scenario: An STO, for a storage to storage location.  An outbound delivery is created for GI, then Goods receipt. When creating the outbound delivery, it reduces the ATP quantity in CO09, and only adds it back upon GR. But,

  • How do I get iWeb on my refurbished Macbook Pro

    I just bought my son a refurbished 13" Macbook Pro (late 2011).   I realize iWeb is on it's way out, but many people are still using it.   The app was not on his Mac.   Is it just a simple matter of copy the file in the apps folder over to his apps f

  • Integrating PDK with OC4J

    Hi friends, I am using PDK with OC4J(9.0.0.2.0) I created a provider.xml, created a provider using Oracle Portal, created a page which contais this provider created, but when I run this page some error messages are being displayed: Exception: oracle.

  • My trackpad will swipe left between full-screen apps, but it will not swipe right

    My Trackpad on my imac will swipe left between full-screen apps, but it will not swipe right. How do I fix this? -m

  • Assignment feild is not pulling through to report FS10N

    Hi, When I run the FS10N and FBL3N, The assignment feild is not pulling through to report FS10N and FBL3N even though we select the assignment feild to be displayed(layout).If we double click on the line item the assignment feild value is appearing.