Regex question: escaping bracket  \[

I get this error when compiling when I try to escape a bracket:
illegal escape character
The code is this:
Pattern p = Pattern.compile("section\[");
I'm trying to match one of these:
Thanks

You need an extra backslash:Pattern p = Pattern.compile("section\\[");

Similar Messages

  • Java Regex Question (HTML Tokenizing

    Hello
    I would like to tokenize a HTML Page into its html tags and could not find any working expression. I tried it with:
    <[.]*>
    and for all input fields:
    <(INPUT.*)>
    But it doesn't find anything either or it findes anything.
    Can somebody help me?

    </?\S+?[\s\S+]*?>
    "/?" means: "/" can be there but doesnt have to
    "\S" means: every character which isnt a whitespace
    "+" means: look for the previous character if it is there at least one time.
    the "?" after the "+" means: look only for as few of the previous characters as needed to fullfill the regex.
    thats why <adf>sdf> isnt found because <adf> is the shortest string that fullfills the regex.
    "[]" means: treat everything inside the brackets as one term
    "\s" means: look for a whitespace
    "*" means: the previous character (which is the term inside the brackets) can be there as many times as it wants, even zero times
    "*?" is like "+?"

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

  • ACE Probe regex and escaping Parenthesis

    I'm trying to setup a ACE probe that expects a return of
    (server.domain.com) EXISTS=TRUE,AVAILABLE=TRUE,ACTIVE=TRUE
    But it doesn't appear that I can use Parenthesis inside a regex.  I've tried escaping as well.
    expect \(server\.domain\.com\) EXISTS=TRUE,AVAILABLE=TRUE,ACTIVE=TRUE
    % invalid command detected at '^' marker.   Pointing at the (
    But this doesn't work either.  Any ideas?

           Hi,
    Hi,
    If it has taken it, it should match the response from server.  Is it still not matching?
    If you look at the regex builder below, the regex matches the response which is expected from the server. So ACE should be able to match it.
    Also, you can try and put \ before dots but not sure. In my opinion it should work fine with what we have put in already. If it doesn't we will have to use hit and trial. Let me know if you need this regex builder. You can download it from google though. In any case i just attached it.

  • Java Regex Question extract Substring

    Hello
    I've readt the regex course on http://www.regenechsen.de/regex_de/regex_1_de.html but the regex rules described in the course and its behavior in the "real world" doesn't makes sense. For sample: in the whole string: <INPUT TYPE="Text" name="Input_Vorname">
    the matcher should extract only the fieldname so "Input_Vorname" i tried a lot of patterns so this:
    "name="(.*?)\"";
    "<.*name=\"(.*)\".?>";
    "<.*?name=\"(w+)\".*>";
    "name=\".*\"";
    and so on. But nothing (NOTHING) works. Either it finds anything or nothing. Whats wrong ?
    Can somebody declare me what I've made wrong and where my train of thought was gone wrong?
    Roland

    When you use the matches() method, the regex has to match the entire input, but if you use find(), the Matcher will search for a substring that matches the regex. Here's how you would use it:  String nameRegex = "name=\"(.*?)\"";
      Pattern namePattern = Pattern.compile(nameRegex,Pattern.CASE_INSENSITIVE);
      Matcher nameMatcher = namePattern.matcher(token);
      if (nameMatcher.find()) {
        String fieldName = nameMatcher.group(1);
      }But the main issue is that you're using the wrong method(s) to retrieve the name. The start() and end() methods return the start and end positions of the entire match, but you're only interested in whatever was matched by the subexpression inside the parentheses (round brackets). That's called a capturing group, and groups are numbered according to the order in which they appear, so you should be using start(1) and end(1) instead of start() and end(). Or you can just use group(1), as I've done here, which returns the same thing as your substring() call.
    Knowing that, you could go ahead and use matches(), with an appropriate regex:  String nameRegex = "<.*?name=\"(\\w+)\".*?>";
      Pattern namePattern = Pattern.compile(nameRegex,Pattern.CASE_INSENSITIVE);
      Matcher nameMatcher = namePattern.matcher(token);
      if (nameMatcher.matches()) {
        String fieldName = nameMatcher.group(1);
      }

  • Simple Java regex question

    I have a file with set of Name:Value pairs
    e.g
    Action1:fail
    Action2:pass
    Action3:fred
    Using regex package I Want to get value of Name "Action1"
    I have tried diff things but I cannot figure out how I can do it. I can find Action1: is present or not but dont know how I can get value associated with it.
    I have tried:
    Pattern pattern = Pattern.compile("Action1");
    CharSequence charSequence = CharSequenceFromFile(fileName); // method retuning charsq from a file
    Matcher matcher = pattern.matcher(charSequence);
    if(matcher.find()){
         int start = matcher.end(0);
         System.out.println("matcher.group(0)"+ matcher.group(0));
    how I can get value associated with specific tag?
    thanks
    anmol

    read the data from the text file on a line basis and you can do:
    String line //get this somehow
    String[] keyPair = line.split(":")g
    System.out.println(keyPair[0]); //your name
    System.out.println(keyPair[1]); //your valueor if you've got the text file in one big string:
    String pattern = "(\\a*):(\\a*)$"; //{alpha}:{alpha}newline //?
    //then
    //do some things with match objects
    //look in the API at java.util.regex

  • SQL Question - Escaping values

    I am using java.sql and need to do a simple "insert into ..." command. The problem is i can not find a escape funtion.. or anything in the package that will escape the characters that need to be escaped.
    ex of what i need:
    statement.executeUpdate("INSERT INTO " + getTableName() + " (COL_1) VALUES ('" + escape(value) + "')");
    I need the escape function above.
    Is there a method in the java.sql package that does this????
    If not does someone know where to get one that is already coded.

    I am using java.sql and need to do a simple "insert
    into ..." command. The problem is i can not find a
    escape funtion.. or anything in the package that will
    escape the characters that need to be escaped.Well, at least you're aware of the issue. I've come across alleged software engineers who wouldn't concern themselves with it.
    However, this is not the right way to go about this. You should use parameter markers, ie, ? characters, and the PreparedStatement.set(...) methods to set the parameter values. Apart from anything else, concatenating strings to form SQL statements defeats any attempts by the underlying database software to cache prepared statements.
    If you're really determined to pursue the course you've outlined, then all you need is to duplicate any ' characters in most literals. The exception being literals used in a LIKE clause, where you also need to escape the % character and the escape character itself, using an escape character defined by the SQL ESCAPE clause.
    But I repeat, this is not the way to go about it.
    Sylvia.

  • OT: Regex Question

    I'm doing a series of search and replace operations with Dreamweaver and wondered if anyone can suggest a regular expression for a particular situation.
    The following URL is fine as it is:
    <td><a href="http://www.geoworld.org/Brazil" title="Brazil">Brazil</a></td>
    However, I need to replace the spaces in this URL with underscores...
    <td><a href="http://www.geoworld.org/Central African Republic" title="Central African Republic">Central African Republic</a></td>
    The finished URL should like like this:
    <td><a href="http://www.geoworld.org/Central_African_Republic" title="Central African Republic">Central African Republic</a></td>
    In other words, I want to replace ALL spaces in the URL proper with underscores, but I want to leave the spaces in the title attributes and visible text alone. Does anyone know a regular expression that will do this?
    Thanks.

    Find:
    (href="[^"]+)\s([^"]+")
    Replace:
    $1_$2
    This will replace one space with an underscore each href attribute. Run the same regex several times until no more instances are found.

  • Java Regex Question

    I wanted to do some regex to see if a string has a subdomain.
    I want to pass string then check if there is a xxx.example.com or if it's just example.com. Anyone have a clue?
    Thanks,
    Brian

    I just went around and used the split method to check, I'm posting my code in case someone else has this problem and limited to the 1.4 jdk.
    String split = domain.split("[.]") ;
    if(split.length > 2)
        domain = split[split.length - 2] + "." + split[split.lengh -1] ;basically what I wanted to do was see if it was a subdomain and then strip the preceding and just get to the actual domain.
    Thanks for the replys

  • Regex question (does not contain)

    Can anyone tell me what regular expression I could use with Dreamweaver to search for files that do NOT contain the word "physiology"? Ideally, I'd like to find pages that don't contain any variation - physiology, Physiology or PHYSIOLOGY. However, if you have time to show me a couple regex's, including one that's case-sensitive, that would be great.
    I've tried the following two "negative lookaround" regex's without success:
    ^(?:(?!Physiology).)*$
    ^(?!.*Physiology).*
    I think they're both designed to work with strings, not with entire files.
    Thanks.

    Not sure how to do this in DW but I suggest try using Windows FindStr function as explained here:
    http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/findstr.msp x?mfr=true
    Adapt the method to suit your needs.
    Good luck.

  • Regex question: How do I insert commas between meta data?

    Current search engine is being replaced with Google Search Appliance (GSA). It requires meta data to be separated by a comma + space, whereas the previous search engine required only a space.  For example:
    <meta name="C_NAME" content="Screen1 Screen2">
    must become
    <meta name="C_NAME" content="Screen1, Screen2">
    There are 17 unique screen names and each of 2500 html files may have one or more screen names identified in that meta tag field.
    I am hoping for some regular express magic to help me with that global search/replace effort.  Suggestions are greatly appreciated.
    Thanks,
    Rick
    ================================
    Nevermind... figured it out.  Just needed to study regex syntax a bit. Here's the answer:
    Find:  <meta name="C_NAME" content="(\w+)\s(\w+)\s
    Replace:  <meta name="C_NAME" content="$1, $2,

    The only transition you can add this way is default cross dissolve. If the images are in the timeline, move the playhead to the beginning of the images, select them all, and drag from the timeline to the canvas to overwrite with transition.

  • 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 question. Please help!

    I'm trying to capture instances like
    &_l_t_;something&_g_t_;
    &_l_t_;blahblah&_g_t_;I tried the following regular expressions:
    "&_l_t_;.+?&_g_t_;"
    "\\&_l_t_;.+?\\&_g_t_;"but neither worked.
    In the code above, the underscore character should not be there, because i was not able to post my message correctly if i did not use underscore to connect the characters '&', 'l', 't', ';'
    Please help!

    import java.util.regex.*;
    public class TagCheck {
      public static void main(String[] args) {
        String[] codes = {
          "&_lt;html&_gt;", "a&_lt;b", "abc", "&_lt;head&_gt;", "c&_gt;d"
        String code = "^(&_lt;).*(&_gt;)$";
        Pattern codePattern = Pattern.compile(code);
        Matcher match;
        for(int j = 0; j < codes.length; j++) {
          match = codePattern.matcher(codes[j]);
          System.out.println("codes[" + j + "] = " + codes[j]);
          if(match.find())
            for(int k = 0; k <= match.groupCount(); k++)
              System.out.println("\t\t\tgroup " + k + " = " + match.group(k));
    }

  • Regex question. How do I capture this pattern?

    Hi
    How do I capture pattern of strings like this:
    <TagA attr <InnerTagB attr> attr>
    Thanks!

         static private String regex = ".*?(<[^<>]*(?:<.*?>)*.*?>).*";

  • Regex question; $1, $2, etc

    Hi,
    If I have the following regex Pattern set up:
    Pattern title = Pattern.compile("<title>([^<]+)</title>");and I want what's within the parentheses to be stored as a varialbe, the way it would be in perl:
    my $title = $1;or whatever, how do I do that in java? Couldn't find it on any of hte regex tutorials I was looking at.
    thanks,
    bp

    The JDK regex package doesn't store captured groups in local variables like Perl does. Instead, you have to retrieve them from the Matcher using the group(int) methods. However, you can use $1, $2, etc. in the replacement string when you do a replaceAll or replaceFirst, and the Matcher will replace them with the appropriate captured groups.

Maybe you are looking for

  • Zen Vision M 30Gb and Windows 7

    Hi. I have problem with my player. I installed windows 7 and zen media organizer 5. Windows and windows media player 2 detect player. If I want transfer music to my player by creative organizer, organizer writing ,,No Creative MP3 player is detected.

  • How do I transfer my songs from my iPod Touch to my new MacBook Pro?

    Okay so I have read many similar questions, but I have not found any that share my exact problem.  I got an iPod Touch for Christmas and bought songs from the iTunes app it has, NOT FROM A PREVIOUS COMPUTER.  I have boughten 83 songs so far.  Now I j

  • 10.4 kernel panic, now i'm panicked!!!

    Well, here goes... A few weeks ago software update said a new version of OS 10.4.x.x was available, so I started to install it on my imac ppc with isight, purchased in 2005. Then I got an error message saying it didn't install so the package or whate

  • Dynamic proxy API

    where can i learn about Dynamic Proxy API,.. can anyone provide me links for the same... thank you...

  • Pdk download for eclipse 3

    Hi everyone, does anyone know where to download the pdk for eclipse 3.  I have EP 6, not netweaver.  I have downloaded a pdk file, bit it zipped out to an .epa file and I don't know what to do with it. thanks a bunch, Mariana