Regex pattern problem

G'day,
I've been working my way through the Pattern API, and it's been working well for me so far, but I've stumbled on the following point:
How do you represent the "[" or "]" literal characters?
Basically the pattern I'm trying to match is a timestamp that would look like [00:00], so I'm looking for a pattern like "\[[0-9]{2}:[0-9]{2}\]" (replacing "\[" and "\]"with something that works).
Any help is appreciated.

use DOUBLE backslash to escape special symbols (since the first one is ate by javac)

Similar Messages

  • Regex pattern, filter delimiter in sql code

    Hi,
    The problem I'm having is that the regex pattern below is not catching the beginning "go" and ending "go" of a string.
    "(?iu)[(?<=\\s)]\\bgo\\b(?=\\s)"
    The idea is catching the "whole word", in this case the word is "go" so if the word is at the beginning of the string or at the end, i still want to include it.
    So, for example:
    "go select * from table1 go" -> should catch 2 "go"s but catches 0
    "go go# select * from table1 --go go" -> should also catch 2 "go"s but catches 0
    "go go select * from table1 go go" -> should catch 4 "go"s but catches 2
    I have the "[(?<=\\s)]" and the "(?=\\s)" so that the word "go" when next to a special character is not included, for example "--go".
    The problem is that this also negates the beginning and ending of the string.
    Code to test example: It should split at 1st, 2nd and last "go", but only splits at the 2nd "go".
    String s = "go go select * from table1 --go go";
    String delimiter = "go";
    String[] queries = s.split("(?iu)[(?<=\\s)]\\b" + delimiter + "\\b(?=\\s)");
    for (int i = 0; i < queries.length; i++) {
         System.out.println(queries[i]);
    I really need to fix this but I'm not having much success.
    Any help will be appreciated, thanks in advance.

    Yes,
    I prefer this one: Regex Powertoy (interactive regular expressions)
    It's not 100% perfect, but you can see with my example and this online tester that the 1st "go" is not matched. And this is a problem for me.
    I want to eliminate the special characters like "#go" or "-go" but i don't want to eliminate the end and start of string.

  • Java Regex Pattern

    Hello,
    I have parsed a text file and want to use a java regex pattern to get the status like "warning" and "ok" ("ok" should follow the "warning" then need to parser it ), does anyone have idea? How to find ok that follows the warning status? thanks in advance!
    text example
    121; test test; test0; ok; test test
    121; test test; test0; ok; test test
    123; test test; test1; warning; test test
    124; test test; test1; ok; test test
    125; test test; test2; warning; test test
    126; test test; test3; warning; test test
    127; test test; test4; warning; test test
    128; test test; test2; ok; test test
    129; test test; test3; ok; test testjava code:
    String flag= "warning";
              while ((line= bs.readLine()) != null) {
                   String[] tokens = line.split(";");
                   for(int i=1; i<tokens.length; i++){
                        Pattern pattern = Pattern.compile(flag);
                        Matcher matcher = pattern.matcher(tokens);
                        if(matcher.matches()){
    // save into a list

    sorry, I try to expain it in more details. I want to parse this text file and save the status like "warning" and "ok" into a list. The question is I only need the "ok" that follow the "warning", that means if "test1 warning" then looking for "test1 ok".
    121; content; test0; ok; 12444      <-- that i don't want to have
    123; content; test1; warning; 126767
    124; content; test1; ok; 1265        <-- that i need to have
    121; content; test9; ok; 12444      <-- that i don't want to have
    125; content; test2; warning; 2376
    126; content; test3; warning; 78787
    128; content; test2; ok; 877666    <-- that i need to have
    129; content; test3; ok; 877666    <-- that i need to have
    // here maybe a regex pattern could be deal with my problem
    // if "warning|ok" then list all element with the status "warning and ok"
    String flag= "warning";
              while ((line= bs.readLine()) != null) {
                   String[] tokens = line.split(";");
                   for(int i=1; i<tokens.length; i++){
                        Pattern pattern = Pattern.compile(flag);
                        Matcher matcher = pattern.matcher(tokens);
                        if(matcher.matches()){
    // save into a list

  • Applying REGEX-pattern into XML File

    I have the following problem:
    I have an xml-file. let's say...
    <NODE><NODE1 attr1="a1" attr2="a2">
         <NAME> abc</NAME>
         <VERSION> 1.0</VERSION>
    </NODE1>
    <NODE2 attr1="a3" attr2="a4">
         <NAME> xyz</NAME>
         <VERSION> 3.1</VERSION>
    </NODE2></NODE>I need to know "HOW can I get the values of <NAME></NAME> and <VERSION></VERSION> without using DOM.
    Since my xml-file is pretty big and DOM will take much Memory, i want to avoid it.
    Can anybody suggest some "Regex pattern" so that i can apply it on the xml-file (after converting into String)
    Thanks in Advance

    That worked perfectly. I assumed ( insert comment here ) that the members of the Properties objects were Strings, and therefore followed the same rules where "\" characters are concerned.
    Thank you for pointing out the difference between the two objects, I am not sure how long it would have taken me to figure that out.
    Regards,
    John Gooch

  • Regex related problem

    Friends,
    I'm trying to create a regex to verify that a given string only has characters a-z or A-Z
    Hi Friends,
    I'm trying to create a regex to verify that a given string only has characters a-z or A-Z.
    Examples:
    1. "abcdef" = true;
    2. "a2bdef" = false;
    3. "333" = false;
    4. "j" = true;
    I'm using the below code.
    //Pattern Matching
                // Create a pattern
                Pattern p = Pattern.compile("[a-zA-Z]");
            // Create a matcher with an input string
                Matcher m = p.matcher("AB56CD");
                boolean result = m.find();
                if(!result)
                    JOptionPane.showMessageDialog(null,"Only characters are            allowed","Alert",JOptionPane.ERROR_MESSAGE);
                    check = false;
                //Patern MatchingFor the given string I'm getting true for the result variable. But I'm supposed to get false & display the error message. I'm not getting where is the problem in the regex pattern.
    My second query is how can I ensure that my given string would be 25 letters long. Would ^[a-zA-Z]{1,25}$
    regex work?
    thanks in advance.

    Your patterns says that you want to match a string that contains only a single a-z A-Z character so if you have more than one it will fail. You need something like
    Pattern p = Pattern.compile("[a-zA-Z]*");to include the empty string orPattern p = Pattern.compile("[a-zA-Z]+");if there must be at least one character orPattern p = Pattern.compile("[a-zA-Z]{3,33}");if there must be between 3 and 33 inclusive characters.
    Visit [http://www.regular-expressions.info/|http://www.regular-expressions.info/] to learn more about regex.

  • Regex Pattern For this String ":=)"

    Hello All
    True, this isn't the place to ask this but here it is anyway, if you can help please do.
    Can anybody tell me the regex pattern for this String:
    ":=)"
    Thanks
    John

    Yep, cheers it's ":=\\)"
    public class Test {
         public static void main( String args[] ) {
              String s = "one:=)two:=)three:=)four";
              String ss[] = s.split( ":=\\)" );
              for( int i=0; i<ss.length; i++ )
                   System.out.println( "ss["+i+"] = {" + ss[i] + "}" );
    }resulting in:
    ss[0] = {one}
    ss[1] = {two}
    ss[2] = {three}
    ss[3] = {four}

  • Util.regex.Pattern documentation

    The 1.5 documentation for util.regex.Pattern defines quantifiers that are greedy, reluctant, or possessive. The definitions of these quantifiers seem to be the same. For example, X?, X??, and X?+ are each defined as "X, once or not at all." Is this a mistake? If not, what's that difference among greedy, reluctant, and possessive?

    It's not a mistake, it's just incomplete. A normal (greedy) quantifier matches as many times as it can, but will back off if necessary to achieve an overall match. A reluctant quantifier matches the minimum number of times that it has to, and only tries to match more if that's the only way to achieve an overall match. A greedy quantifier matches as many times as it can and never backs off, even if that makes an overall match impossible. Here's a demonstration:import java.util.regex.*;
    public class Test
      public static void main(String[] args)
        String input = "XXXXX";
        Pattern p1 = Pattern.compile("(X+)(X+)");
        Pattern p2 = Pattern.compile("(X+?)(X+)");
        Pattern p3 = Pattern.compile("(X++)(X+)");
        Matcher m = p1.matcher(input);
        if (m.matches())
           System.out.println("p1:\t" + m.group(1) + "\t" + m.group(2));
        m = p2.matcher(input);
        if (m.matches())
           System.out.println("p2:\t" + m.group(1) + "\t" + m.group(2));
        m = p3.matcher(input);
        if (m.matches())
           System.out.println("p3:\t" + m.group(1) + "\t" + m.group(2));
    p1:     XXXX    X
    p2:     X       XXXXIn p1, the X+ in the first group initially matches all five X's, then hands off to the second group. The X+ there has to match at least one X, but there are none left. So the first group gives up one of its X's, the second group matches it, and Bob's your uncle.
    In p2, the X+? has to match at least one X, so it does, then hands off to the second group, which happily gobbles up the rest of the input.
    In p3, the X++ matches all the X's, but refuses to back off and give the X+ in the second group the one X it needs, so the match fails.

  • Searching Site Content Using REGEX Patterns

    Intent: Detect content in SharePoint 2013 lists and libraries that matches a REGEX pattern, like social security numbers.
    SharePoint 2013 only exposes KQL and FQL languages. 
    http://msdn.microsoft.com/en-us/library/office/jj163973.aspx
    I am comfortable writing this as an App.  I do not know how to pass the search index through a REGEX match.  Perhaps there is a way to access the data on more of a server model instead of through the client APIs?

    Hi  Eric,
    For achieving your demand, you can write a Content Enrichment Web Service to extract regex patterns from a managed property.
    Here is a blog you can refer to:
    SharePoint 2013 Content Enrichment: Regular Expression Data Extraction:
    http://blogs.technet.com/b/peter_dempsey/archive/2013/12/04/sharepoint-2013-content-enrichment-regular-expression-data-extraction.aspx
    Reference:
    http://msdn.microsoft.com/en-us/library/office/jj163982.aspx
    http://blogs.msdn.com/b/richard_dizeregas_blog/archive/2013/06/19/advanced-content-enrichment-in-sharepoint-2013-search.aspx
    Thanks,
    Eric
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support,
    contact [email protected]
    Eric Tao
    TechNet Community Support

  • Regex - Pattern for positive numbers

    Hi,
    I wanna check for positive numbers.
    My code so far:
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(str);
    boolean b = m.matches(); But I don't know how to check for positive numbers (including 0).
    Thanks
    Jonny

    Just to make your life easier:
    package samples;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    * @author notivago
    public class Positive {
        public static void main(String[] args) {
            String input = "- 12 +10 10 -12 15 -12,000 10,000 5,000.42";
            Pattern p = Pattern.compile( "\\b(?<!-\\s?|\\.|,)([0-9]+(?:,?[0-9]{3})*(?:\\.[0-9]*)?)" );
            Matcher matcher = p.matcher( input );
            while( matcher.find() ) {
                System.out.println( "Match: " + matcher.group(1) );
    }

  • Ava.util.regex.pattern and * - + /

    hi...
    i'm korean... so I can't speak english.. sorry..^^
    but i hava a problem..
    import java.util.regex.*;
    public class Operator
    /     public static void main(String args[])
              String operator="/";
    ////////////////////////////////////////////////////////////// error point..
              Pattern pattern=Pattern.compile(operator);
              Matcher m=pattern.matcher("- ----* / */* /+");
              int count=0;
              while(m.find()) {
         count++;
              System.out.println(count);
    Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
    +
    operator : / - : ok...
    operator : * + : error...
    i had to use + *..
    what's problem??

    Are you using matches()? Then keep in mind that it requires that the entire String is matched by the RE.
    pattern.matcher("about:foobar").matches(); //will return false, as "foobar" is not matched by your pattern
    pattern.matcher("about:").matches(); //will return true
    pattern.matcher("about:foobar").find(); //will return true
    pattern.matcher("notabout:foobar").find(); // will return false

  • Regex Pattern Match in an extremely long string

    I need to search a file containing 1 extremely long line (approximately 1 million characters), The pattern I want to search is "ABC" as long as it appears at least n times whatever user input as n. I need the position of where this pattern is found. How to best do this? I tried to break the input into blocks of 100000 characters at a time as too many characters read cause the 'java out of memory' error to occur.
    Then I converted this to a string in order to use REGEX to search. My problem is how to ensure that the last few characters of the current block is also being searched too? How to write the regex expression to do this? Will breaking the input file into multiple lines help?
    eg:
    Searching for ABC as long as it appears at least 3 times continuously ie (ABCABCABC)
    Original Line = XXXXXXXABCABCABCXXXXXXABCX
    The first block of 10 characters read is XXXXXXXABCABC
    The second block of 10 characters read is ABCXXXXXXABCX
    The search result should be position 7 and position 22

    If the sequence of characters is longer than a few hundred KB, then turning it into a String requires you to have enough heap space available in the JVM to store the entire String.
    If that is a problem, an alternative solution is to have a while loop over an InputStream that reads from the source of characters (a file, a network connection, stdin etc.) and looks for the string. Keep a ring buffer the size of the query string, and read the data from the InputStream into it. Then for each character read, compare the content of the ring buffer to the query string.
    This way you will not use more heap space than the size of the query-string, and the size of whatever buffer you use in your InputStream (8KB for the empty constructor of BufferedInputStream at the moment) plus the odds'n ends from the implementation.

  • Illustrator 5 - patterns problem with printing

    Hi please please help having majoy problems and need help asap in work!!!
    I am working on a PC windows 7 illustrator 5.
    when I create a pattern any type even a imple spot and fill a CAD t shirt, its fine, when I print it, it creates lines through out either vertica/horizonal when I send to someone else to print its fine when i print on another printer its fine. when using default pattern swatches from illutstrator it prints fine, it seems to be when I fill a flat CAD with a pattern and I have created it.
    Is this something to do with printer? I need ergent help its driving me crazy have asked loads of IT people everyone is stuck even my collegues who have worked with software for years.
    please please help!! I have tried everythint, loads of diffrent pattens and colours nothing is fixing, lines still show on pdf doc too.

    Illustrator 5 is more than a decade old. If you really mean version 5, you may be hard pressed to find much help.
    If by chance you mean CS5 (version 15) that's another matter.
    Does the problem exisit in a new document or only in specific documents?
    Have you tried trashing the Ai settings?
    The fact that someone else can print it... as well as switching printers works, would lead to a issue with your print driver for the specific printer showing the issue. Or perhaps a combination of the print driver and the artwork construction. For example, the printer only handles Postscript level 2 and you need Postscript level 3 support to print the artwork properly.

  • Using special chars in RegEx causes problems

    Hello Folks,
    I have a single string of numbers positive and negative separated by a delimiter. I am trying to convert the negative numbers which are represented by brackets into ones without brakcets e.g. (1.235) to -1.235
    Here is what I have in my code
                   arCols[j].replaceAll("\(", "-");
                   arCols[j].replaceAll("\)", "");
    But that gives a compilation problem as below.
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
         Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
    And if I remove the leading slash that tries to escape the character as below
                   arCols[j].replaceAll("(", "-");
                   arCols[j].replaceAll(")", "");
    I get the following error.
    Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1
    How can I replace the brackets using regular expression search and replace?
    Thanks for your help.
    Sanjay.

    You need
    arCols[j] = arCols[j].replaceAll("\\(", "-");
    arCols[j] = arCols[j].replaceAll("\\)", "");because
    a) String objects are immutable
    and b) you need to escape the '(' and ')' .
    P.S. With a bit of thought this could be done in one single regex
    System.out.println("fasdf(123.4)faf fdf(246.8) fafasd 1.23".replaceAll("\\(([^\\)]*)\\)","-$1"));Edited by: sabre150 on Oct 2, 2007 7:32 AM

  • Regex Pattern help.

    Me and my friend pedrofire, that�s probably around forums somewhere, are newbies. We are trying to get a log file line and process correctly but we are found some dificculties to create the right expression pattern.
    My log have lines like:
    User 'INEXIST' with session 'ax1zjd8yEeHh' added content '769' with uri 'http://mail.yahoo.com/'.
    User 'INEXIST' with session 'ax1zjd8yEeHh' changed folder from 'E-mails' to 'Milhagem'.
    User 'INEXIST' with session 'a8jXrY_N38ja' updated all content of folder 'Bancos'.
    i need to get the following data
    USER - [INEXIST]
    SESSION - [ax1zjd8yEeHh]
    ACTION - [added] or [changed] or [updated].
    Getting the user and the session is easy, but i am having difficulties grabing the action, because i need to take just the action word without blank spaces igonring the words content or folder or all.
    I m trying this for hours, but to a newbie is a little dificult
    Any help is welcome
    Thanks
    Peter Redman

    Hi,
    How about something like:
    import java.util.regex.*;
    public class RegexpTest
       private static final Pattern p = Pattern.compile(
             "^User '([^']+)' with session '([^']+)' ([^ ]+) .*$" );
       public static void main( String[] argv )
          find( "User 'INEXIST' with session 'ax1zjd8yEeHh' added content '769' with uri 'http://mail.yahoo.com/'." );
          find( "User 'INEXIST' with session 'ax1zjd8yEeHh' changed folder from 'E-mails' to 'Milhagem'." );
          find( "User 'INEXIST' with session 'a8jXrY_N38ja' updated all content of folder 'Bancos'." );
       public static void find( String text )
          System.out.println( "Text: " + text );
          Matcher m = p.matcher( text );
          if ( ! m.matches() ) return;
          String user = m.group(1);
          String session = m.group(2);
          String action = m.group(3);
          System.out.println( "User: " + user );
          System.out.println( "Session: " + session );
          System.out.println( "Action: " + action );
       }which results in:
    Text: User 'INEXIST' with session 'ax1zjd8yEeHh' added content '769' with uri 'http://mail.yahoo.com/'.
    User: INEXIST
    Session: ax1zjd8yEeHh
    Action: added
    Text: User 'INEXIST' with session 'ax1zjd8yEeHh' changed folder from 'E-mails' to 'Milhagem'.
    User: INEXIST
    Session: ax1zjd8yEeHh
    Action: changed
    Text: User 'INEXIST' with session 'a8jXrY_N38ja' updated all content of folder 'Bancos'.
    User: INEXIST
    Session: a8jXrY_N38ja
    Action: updatedYou should probably change the Pattern to be less explicit about what it matches. i.e. changes spaces to \\s+ or something similar.
    Ol.

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

Maybe you are looking for

  • F.13 Clearing Issue

    Hi, We have posted MIRO document for a particular GL account.During this entry the GRIR account got debited instead of credit, so we passed a manual JV through F-05 to debit the GRIR account. Now I want to clear GRIR account Debit and Credit balance

  • Error message: "Install Excel as viewer"  BRAIN871

    Hello Experts, I have installed SAP GUI 7.20 and all BW patches. Also installed the BE Analyzer But when I try to run Tr. RRMX.... I receive error message  BRAIN871 "Install Excel as viewer"  Know somebody any solution? Regards Juan

  • AS/400 Source query

    Guys, I had a query regarding taking count from AS/400 source table after Interface loads the data successfully. Currently iam doing this through ODI Procedure with the following query and it works well. select count(*) AS YYY1732WP_COUNT from XXX.DW

  • Enhancing NUMBER_GET_NEXT when RETURNCODE is 1

    Hi, When NUMBER_GET_NEXT  return '1' we know that critical value reached. This return code set within NUMBER_GET_NEXT  >> PERFORM LOCAL_BUFFER routine. Requirement: when ever NUMBER_GET_NEXT returns '1' i have to send a mail to some fixed mail id. Th

  • How do I create a flashing light when thunder rolls using Motion?

    I'll like to create a flash of light from outside a window in a scary scene when the lightning and thunder rolls. Does anyone know how to do this in motion? I have motion 3 thanks