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

Similar Messages

  • JAVA Regex Illegal Characters

    Hello - I am trying to find a list of all illegal characters which have to be escaped in JAVA Regex pattern matching but I cannot find a complete list.
    Also I understand that when doing the replaceall function that there is a special list of characters which can't be used for that as well, which also have to be escaped differently.
    If anyone has access to a full complete list as to when to escape and how I would greatly appreciated it!
    Thanks,
    Dan

    I also noticed this below link:
    http://java.sun.com/docs/books/tutorial/extra/regex/literals.html
    It said the following characters are meta-characters in regex API:
    ( [ { \ ^ $ | ) ? * + .
    But it also says the below:
    Note: In certain situations the special characters listed above will not be treated as metacharacters. You'll encounter this as you learn more about how regular expressions are constructed. You can, however, use this list to check whether or not a specific character will ever be considered a metacharacter. For example, the characters ! @ and # never carry a special meaning.
    Does anyone know if there would be any issues if I escaped when a character didn't need to be escaped?

  • How do you get java regex to match two different pattern

    Hi,
    I am having trouble getting getting java regex to match two pattern: "unknown host" or "100%".
    Here is a snippet of my code:
    try{
    Process child = Runtime.getRuntime().exec(" perl c:\\ping.pl");
    BufferedReader in = new BufferedReader( new InputStreamReader( child.getInputStream() ));
    String patternStr = "(unknown host | 100 %)";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(" ");
    String line = null;
    while ( (line = in.readLine()) != null){
    System.out.println(line);
    matcher.reset(line);
    if (matcher.find())
    // line matches throws pattern
    System.out.println("match string");
    else
    System.out.println("no matches");
    I thought the "|" means OR but somehow it is not working.
    kirk123

    Hi,
    with String patternStr = "(unknown host | 100 %)"; you are looking
    for the strings "unknown host " OR " 100 %", with the spaces after host and before 100.
    Try "(unknown host|100 %)"
    hope, this will help you

  • Non greedy Java Regex not working

    I am trying to parse some HTML and using regex for it.
    Here is the HTML I want to parse:
    <a href="google.com">Lololo</a> <a href="tttt.com">Read More</a>I want to find the second anchor tag with "Read More" text only.
    The Regex I am using to parse the String is:
    <a.*?>\s*Read More.*?</a>But I am still getting the entire string back after the regex match instead of only the second A tag with Read More text.
    Can anyone help explain what is wrong in my regex?
    I am using Java 6 with Eclipse IDE 3.4.

    danbrown wrote:
    import java.util.regex.*;
    class TestRegEx {
    public static void main(String[] args) {
    String regex = "<a.*?>\\s*Read More.*?</a>";
    String toChk = "asfafadsfasfadsf <a href="google.com">Lololo</a> d ds <a href="tttt.com">Read More</a> zzzzzz";
    String cleanStr = Pattern.compile(regex,Pattern.CASE_INSENSITIVE).matcher(cleanStr).replaceAll("")
    //Expected output should be "asfafadsfasfadsf <a href="google.com">Lololo</a> d ds zzzzzz"
    //Only the '<a href="tttt.com">Read More</a>' must be deleted no other part of the String must be deleted.
    System.out.println(cleanStr);
    You've stated what the expected output is, but left off what the actual output is. Although in all fairness, there can't be any actual output, since that code will not compile.

  • Java regex

    Hi, I'm pretty new to Java, coming from a JavaScript background. I'm currently doing (or trying) a few challenges from a Java book that I have (Java Programming - For The Absolute Beginner). The challenge that I'm currently attemping asks me to write an application that calculates a 5% tax for any given amount, the problem is... I want to make my program accept both integers and real numbers. I thought it would be pretty straightforward to write two regular expressions, one to match an integer (1-99) and one to match a real number (0-99.0-99), and then, depending on whether the user input was a match to an integer or a real number; convert the match to either an int or float, then assign it to the appropriate variable type instance, I'm having a few problems :)
    Here's my code (I know it contains loads of errors, lol) -
    Challenge01.java
    import java.io.*;
    import java.text.DecimalFormat;
    import java.util.regex.*;
    public class Challenge01 {
      public static void main(String args[]) {
        //Declaration
        int anyPrice;
        float fivePercentTax;
        //Assignment
        anyPrice = 0;
        fivePercentTax = 0.05F;
        String value;
        //Regex
        Pattern intPattern = Pattern.compile("d");
        Pattern floatPattern = Pattern.compile("d.d+");
        //Declaration of a buffer
        BufferedReader reader;
        //Create an instance of the buffer
        reader = new BufferedReader(new InputStreamReader(System.in));
        //Format the data
        DecimalFormat twoDigits = new DecimalFormat("0.00");
        //Prompt for user input
         System.out.print("\t Enter a number:\t");
          value = reader.readLine();
          if value == intPattern {
             anyPrice = Integer.parseInt(value);
          else anyPrice = Float.parseFloat(value);
        System.out.print("\t" anyPrice);
    }Thanks in advance for any help :)

    Saying "it has problems" doesn't mean much to anybody. What does it do and what it is supposed to do?
    You may want to take a look at your regular expressions.
    Pattern intPattern = Pattern.compile("d");Will match the letter 'd' once. You have to escape the 'd' using \\d in order for it to match digits. Secondly, add a '+' to make it match one or more characters instead of only one.
    Also, this line
    else anyPrice = Float.parseFloat(value);won't work. An int cannot be assigned a float value.
    Edited by: codingMonkey on 2008/10/15 03:59

  • Java regex problem

    Hi:
    I have the following texts in a flat file:
    scheduler is running
    system default destination: llp
    device for ps3: /dev/ps3
    device for ps: /dev/ecpp0
    device for llp: /dev/ecpp0
    How can I use java regex to print out the string after "device for " in this case the string "ps3" ,"ps" and "llp".

        static final Pattern DEVICE_PATTERN = Pattern.compile(
                                          "device for ([^:]++)" );
        String text = "";
        Matcher m = DEVICE_PATTERN.matcher( text );
        while ( (text = bufferedReader.readLine()) != null ) {
            if ( m.reset(text).lookingAt() ) {
                String device = m.group( 1 );
        }

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

  • Java regex - eval for replacement

    Hi
    Could you please help me in a regex problem?
    I have a regex pattern in a string. I want to apply this on a text, and wherever it is applied the matched text should be replaced by the length of the found text. Now I have done it with a while loop, but it takes too long to process:
                   Pattern p = Pattern.compile(patternString);
                   Matcher m = p.matcher(text);
                   // I dont know how to get this job done with m.replaceAll(). Thats why the following loop
                   // By the way, in Perl there is "eval" with which we can do this
                   while (m.find()) {
                        String foundText = m.group();
                        Pattern p2 =  Pattern.compile( Pattern.quote(foundText) );
                        text = p2.matcher(text).replaceAll( foundText.length() );
                   }Is there a better way? Kindly help.
    Thanks
    Sri

    There's nothing like Perl's /e modifier (or Ruby's gsub) in Java's regex support, but ther's a much better alternative to what you're doing. In addition to replaceAll() and replaceFirst(), Matcher provides the lower-level methods appendReplacement() and appendTail() that offer you more control over the replacement process. Check this out: Pattern p = Pattern.compile(patternString);
    Matcher m = p.matcher(text);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
      m.appendReplacement(sb, String.valueOf(m.group().length()));
    m.appendTail(sb);
    text = sb.toString(); Or you could just use Elliott Hughes' Rewriter class. (You may need to get rid of some code in the main() method that references other utility classes of his; Rewriter itself only depends the java.util.regex package.)

  • Java Regex, how do I replace \\ with \\\\?

    Hello,
    The following line doesn't work: someString.replaceAll("\\", "\\\\");
    The error I get is the following:
    Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
    ^
         at java.util.regex.Pattern.error(Unknown Source)
         at java.util.regex.Pattern.compile(Unknown Source)
         at java.util.regex.Pattern.<init>(Unknown Source)
         at java.util.regex.Pattern.compile(Unknown Source)
         at java.lang.String.replaceAll(Unknown Source)
         at TSPEngine.main(TSPEngine.java:34)
    How do I fix this?
    Thanks in advance,

    Interference wrote:
    Hello,
    The following line doesn't work: someString.replaceAll("\\", "\\\\");
    The error I get is the following:
    Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1"\\" is how you represent "\" in a String literal in Java, since "\" is an escape character. But "\" is also an escape character in regular expressions, meaning to represent a literal "\" in a Java regex you need "\\\\". Your second string should be fine since it's not interpreted as a regular expression to my knowledge.
    Edit:
    No, the second string DOES need to be "\\\\\\\\".
    Edited by: endasil on 17-May-2010 11:46 AM

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

  • Converting sed regex to Java regex

    I am new to reguler expressions.I have to write a regex which will do some replacements
    If the input string is something like test:[email protected];value=abcd
    when I apply the regex on it,this string should be changed to test:[email protected];value=replacedABC
    I am trying to replace test.com and abcd with the values i have supplied...
    The regex I have come up with is in sed
    s/\(^.*@\)\(.*\)$/\1replaceTest.com;value=replacedABC/i
    Now I am trying to get the regex in Java,I would think it will be something like (^.*@\)(.*\)$\1replaceTest.com;value=replacedABC
    But not sure How i can test this.Any idea on how to make sure my java regex is valid and does the required replacements?

    rsv-us wrote:
    Yep.Agreed.
    Since that these replacements should be done in a single regex.Note that the sed replacement I posted is really made of two replacements! Just like your Java solution would.
    I think once we send this regex to the third party,they will haev to use either sed or perl(will perl do this replacements,not sure though) to get the output.
    Since we are not sure what tool/software the third party is going to use,I was trying to see how i can really test this.Then I read about sed and this regex as is didn't work,so,I had to put all the sed required / and then the regex had become like s/\(^.*@\)\(.*\)$"/1replaceTest.com;value=replacedabcd/iAgain: AFAIK that does not work. I tried it like this:
    {code}$ echo test:[email protected];value=abcd | sed 's/\(^.*@\)\(.*\)$"/1replaceTest.com;value=replacedabcd/i'and the following is returned:test:[email protected] that we will have to send the java regex to the third party,I was trying to see how i can convert this sed regex to java.If I am right,with jave regex,we won;t be able to all the finds and replacements in a single regex..right?...If this is true,this will leave me a question of whether I need to send the sed regex to the thrid party or If I send java regex,they have to convert that to either sed or perl regex.
    One more question,can we do thse replacement in perrl also,if so,what will the equivalent regex for this in perl?
    I can't understand what you are talking about. The large amount of spelling errors also doesn't help to make it clearer.
    Good luck though.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

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

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

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

  • Java Regex groups with quantifiers.

    I'm a bit stuck on a regex , i want to do something similar to this :
    (dog){6}
    dogdogdogdogdogdog
    and returned I want 6 seperate groups with 'dog' in each one.
    This works fine with jakarta-regexp but when I use the {} quantifiers in Java regex I lose the groupings which i'm looking for and just get a single group with a value of 'dog'
    I'm sure i'm doing something something stupid here and help would be great!

    You can't do this with the SunJDK regex engine without using find() with a Matcher.
    I consider this feature of jakarta-regex to be a bug and reported it (and a couple of other features) as such several years ago. The feature makes it incompatible with most regex engines I have used.

Maybe you are looking for

  • Cannot install windows xp on envy 14

    I purchased a new HP envy 14 pre-installed with windows 7. I bought a new WD Scorpio Blue drive, and am currently trying to install windows xp. The setup program crashes when it finishes loading the drivers and says "Setup is loading windows" My gues

  • Spry drop down formatting won't work in IE

    I've tried the other fixes mentioned on this forum- nothing worked. It looks correct in Mozilla (although the background color doesn't go all the way across the submenu buttons) but in IE instead of displaying vertically, the menu stretches out horiz

  • Interface Problems: DBA = Data Pump = Export Jobs (Job Name)

    Hello Folks, I need your help in troubleshooting an SQL Developer interface problem. DBA => Data Pump => Export Jobs (Job Name) => Data Pump Export => Job Scheduler (Step): -a- Job Name and Job Description fields are not visible. Well the fields are

  • Buffered Reader, how to make a loop to terminate

    Hello, the code uses each line from the input.txt and does whatever we want, it's termination condition is when the next line is null. But this fails to work if the input.txt doesn't have an emptyline after the last line, how to change the code to wo

  • Costing views

    Dear all What is the function of costing views 1 and 2 in material master record, work scheduling view. please explain