Newbie in regex... pb with pattern

Hello,
I want to identify each occurence of -> <tr bgcolor="#f7f7f7"> <- in a html code source, this string could be written like this -> <td class="t2" bgcolor="#f7f7f7"> <-...
I try the fallowing java code to parse it :
Pattern p=Pattern.compile("<tr bgcolor=\"#f7f7f7\">"); <** CORRET ;-) **>or
Pattern p=Pattern.compile("<td[ class=\"t2\"]? bgcolor=\"#f7f7f7\">"); <** FALSE **>or
Pattern p=Pattern.compile("<td[ class=\"t2\"]?? bgcolor=\"#f7f7f7\">"); <** FALSE **>or
Pattern p=Pattern.compile("<td[ class=\"t2\"]?+ bgcolor=\"#f7f7f7\">"); <** FALSE **>which one do I have to use ??
thx
stuuf

In a regex, square brackets are used to create a character class, which means "match any one of this set of characters". You're using a character class to match a specific sequence of characters, which is incorrect. It happens to work in this case, but you should really use grouping (parentheses) for that. For instance, if you only wanted to match tags of the form   <tr bgcolor="#f7f7f7"> or <tr class="t2" bgcolor="#f7f7f7"> but not, e.g.,   <tr class="t1" bgcolor="#f7f7f7"> or <tr bgcolor="#f7f7f7" class="t2"> you could put the class="t2" part in a group and make the group optional, like so:  Pattern p = Pattern.compile("<tr (class=\"t2\" )?bgcolor=\"#f7f7f7\">");For a correct use of character classes, suppose you want to match either tr or td tags with the bgcolor="#f7f7f7" attribute (and you don't care about any other attributes). This slight variation on yawmark's solution would do the trick:  Pattern p = Pattern.compile("<t[dr] .*?bgcolor=\"#f7f7f7\".*?>");If you want to learn more about regexes, here's a good place to start: http://www.regular-expressions.info/

Similar Messages

  • Check string validity with pattern

    hello,
    I want to check the validity of strings given by the user. The only characters authorized are : 'a' to 'z', 'A' to 'Z', '0' to '9', '.', '-', '_', '*', '@' and ' ' (space)
    i want to check this string with a pattern but it does not work.
    Somebody can help me for the pattern because the API javadoc is poor and i have a limited web access in my agency.
    Thanks
       String regex = "[a-zA-Z0-9.*-_@]";
       System.out.println(regex);
       boolean bol = Pattern.matches(regex, field);
       System.out.println(bol);
       ->> result always false for string field="Indy jones";

    try this:
    import java.sql.*;
    import java.io.*;
    import java.util.regex.*;
    import java.util.*;
    public class RegExTest2 {
    public static void main (String args[]) {
    Pattern pat = null;
    Matcher m = null;
    String patternToMatch = "^[a-zA-Z0-9\\.\\*\\-\\_@\\s]+$";
    String line1 = "IndianaJones";
    String line2 = "Indiana Jones";
    String line3 = "Indiana - Jones";
    String line4 = "Indiana&Jones";
    String line5 = "Indiana & Jones";
    String line6 = "  Indiana Jones  ";
    String line7 = "Indiana Jones =";
    pat = Pattern.compile(patternToMatch);
    System.out.println("Pattern to match = " + patternToMatch);
    boolean bol = Pattern.matches(patternToMatch, line1);  
    System.out.println("line1 : expected true and got " + bol);
    bol = Pattern.matches(patternToMatch, line2);  
    System.out.println("line2 : expected true and got " + bol);
    bol = Pattern.matches(patternToMatch, line3);  
    System.out.println("line3 : expected true and got " + bol);
    bol = Pattern.matches(patternToMatch, line4);  
    System.out.println("line4 : expected false and got " + bol);
    bol = Pattern.matches(patternToMatch, line5);  
    System.out.println("line5 : expected false and got " + bol);
    bol = Pattern.matches(patternToMatch, line6);  
    System.out.println("line6 : expected true and got " + bol);
    bol = Pattern.matches(patternToMatch, line7);  
    System.out.println("line7 : expected false and got " + bol);
      } // end main
    } //End Class RegExTest2

  • SELECT with pattern CP '50*' is not working on material numbers MATNR

    Hello,
    I have a specific matchcode for searching on material numbers with a function module as selection method.
    In this function module, the SELECT clause is built dynamically as bellow.
          SELECT (temp3)
            INTO CORRESPONDING FIELDS OF TABLE result_tab  UP TO CALLCONTROL-MAXRECORDS ROWS
             FROM (temp)
             WHERE (temp2) .
    In the "temp2" variable, I use RANGES for the selection simply built with values of SELECT-OPTIONS coming from the search help selection screen.
    I am facing the following problem :
    When a search is executed on material number with the following pattern '50*' --> nothing is found !
    When I run a search on '50575' --> the material number is found !
    I expect it is a problem of convertion routines (external to internal format) but I am not able to fix a solution...
    We are in SAP_BASIS 700.

    I think it can be done.
    I have -    
    CONCATENATE  'Z+_'   '00+' INTO  r_ranges-low .
        r_ranges-sign = 'I'.
        r_ranges-option = 'CP'.
        APPEND r_ranges.
        SELECT  ar_object FROM toasp
          INTO CORRESPONDING FIELDS OF table lt_toasp
           WHERE ar_object IN r_ranges.
    And it returns all values with pattern 'Z_00'.
    (Z1_001, Z1_002 etc.)
    If the pattern '50*' is not working, you could try using '50+++'.
    Regards,
    MaryM

  • Problem with pattern numeric field

    Hi All.
    I tryed to format numeric field with patterns num{zzzzzzzzzzzzzzzzzzz9} or num{99999999999999999999}. But when I enter 20 numeric characters like 12345678901234567890 as a result I got 12345678901234567000. How fix that problem?
    Thanks.

    The result you're getting is correct, because you pattern only allows a period to separate the decimal places.
    Try the following edit pattern:
    num{zzzzzzzzzzz9,99}|num{zzzzzzzzzzz9.99}
    and this display pattern:
    num{zzz.zzz.zzz.zz9,99}

  • Regex for url pattern validation

    Hi,
    I am trying to find a regex for Url pattern validation that is not too restrictive.
    Please let me know, if anyone is using a pattern for their applications.
    Thanks
    Mayank Sharma

    are you talking about xml schema restriction?
    <xs:element name="url">
      <xs:simpleType>
       <xs:restriction base="xs:string">
        <xs:pattern value="(https?://)?[-\w.]+(:\d{2,5})?(/([\w/_.]*)?)?" />
       </xs:restriction>
      </xs:simpleType>
    </xs:element>

  • How can I fill mask with pattern?

    Hi
    Would you please help me? How can a add pattern to a mask? I drew a motion mask on video clip and now I want to fill it with pattern that I made in Photoshop and saved as PSD, what should I do? How can I fill mask with specific pattern?
    Thanks for any help

    AE doesn't directly support a pattern-fill like PS, so here's a workaround (as Mylenium suggested):
    Create a PS document and create a layer filled with the pattern required.
    Import the layer/PSD to AE and place in timeline.
    Place a copy of the masked layer above the Pattern layer.
    On the pattern layer, set the Track Matte to Alpha Matte.
    Read more here:
    http://livedocs.adobe.com/en_US/AfterEffects/8.0/WS3878526689cb91655866c1103906c6dea-7cf9. html

  • Color shift when filling with pattern

    Hello!
    I use the 'define pattern' and 'fill with pattern' feature in photoshop all the time to prepare graphics for print / production in my business. However, I have noticed a small but problematic color shift going from the main image (defined pattern) to the page (filled with pattern). You can see it in the image included here. The main image is vibrant, and lighter and the page behind it is dull and darker. It will print this way too. The main image prints great, and gets approved. But the page layout doesn't match. Both documents are set to sRGB color space when I check the Edit -> Color Settings option. Any ideas how to correct this?  Thanks!!

    Hello, in your screenshot, the first tab in the background has no profile that's what (#) means in the title of the tab, untitled one and two have the same profile as the working space (which tab is visible?), while the one in the foreground as a different profile than the working space that's what (*) means in the title bar.
    So, that tells me they do not have the same profile.
    Also, is there noise or very small textures in the circles? You might want to look at them all with the same magnification.
    Finally, a smart object can be of a different color space than the document that holds it.

  • OLAP universe filter with pattern matching.

    Hi,
    I tried to create both a qaaws and a webi report which contained a filter with pattern matching on an olap universe .  When I ran this it took too long to be usable. I found note 1500666 which says that pattern matching is not supported in MDX and to use BEX query variables instead.
    I have created a bex query with a variable which has "Variable Represents" set to "Selection Option". I can run this query and using the search option I can do a pattern match search. I have built a universe based on this query but the filter that gets created automatically in the universe uses a "Between" operator.
    Does anyone know if it is possible to change the definition of the filter in the  universe so that it does a pattern match search and if so how?
    The end result is that I would like to be able to do a pattern match search on the text description of a BW employee object.
    Thanks
    Quentin.

    It would be better if you post the Filter definition here...
    And why don't you do Pattern matching at BO query panel level??
    Where you can find Matches pattern operator to do same stuff.
    Thank You!!

  • Imac G5 - screen freezes with patterned screen

    Yesterday my Imac G5 suddenly had the whole screen covered with patterns which in turn froze
    the machine up.
    Tried using the hardware test (both quick & extended) found nothing wrong.
    Tried resetting the Pram & Nvram - made no difference
    Tried resetting the SMU - made no difference
    Ran Disk Utility to repair permissions - all OK
    Used DiskWarrior and no problems found.
    Powered off and left it all night and restarted this morning all systems appeared OK
    This evening this problem returned and had to power off again which is where I am now.
    I have looked thru these forums and found reference to faulty capacitors about bulging, leaking etc
    and removed the back but could not see any faults
    Any one have any clues as to what the problem is?
    I would appreciate some help here please
    Alan

    Nobody knows when Apple releases new models, but I think that they usually come out in the spring.
    Or sometimes in the fall. In other words, there is no set time.
    Try calling http://www.synaptech.com/catalog/ as I suggested, they replace logic boards very reasonably.

  • Help required with Pattern (Regex use)

    Hello everybody !!
    I'd like to use the Regex Package to find the following Pattern in the following expression:
    PATTERN = prim*bbb
    INPUT = xxx prim yyy xxx prim aaa bbb ddd
    and I would like to obtain two results in the same matching:
    1=> prim yyy xxx prim aaa bbb
    2=> prim aaa bbb
    When I try I obtain just the first one as you can see below:
    Current REGEX is: prim.*bbb
    Current INPUT is: xxx prim yyy xxx prim aaa bbb ddd
    Nombre de groupe =0
    I found the text "prim yyy xxx prim aaa bbb" starting at index 4 and ending at i
    ndex 29.
    Could you help me to cope with regex in order to define such Pattern and obtain these results.
    Thanks a lot !!

    Ok here is something that I wrote up.
    Keep in mind I do not have java 1.4 installed so I could not compile nor test this code.
    It seems like a crazy way to do it , but I can't think of any other way at this time.
    Basically find the String, Trim off the prim and bbb and try to find it again, repeat untill there is not a gap between prim and bbb or maybee a gap of only 1 , was not sure what your exit point would be.
    Hopefully maybee this will help , or not confuse. :-)
    while(matcher.find()) {
    String matchedString = matcher.group();
    System.out.println("I found the text \"" + matcher.group()
    + "\" starting at index " + matcher.start()
    + " and ending at index " + matcher.end() + ".");
    // call this method to search for inner matches
    findInnerMatch(matchedString);
    public void findInnerMatch(String matchedString,String regex) {
    // get the string between prim and bbb *** check index's etc...
    String innerString = matchedString.substring(matchedString.indexOf("prim"),matchedString.lastIndexOf("bbb")-1);
    // make a new pattern with same regular expression
    Pattern pattern = Pattern.compile(regex);
    // make a new matcher with the inner string portion
    Matcher matcher = pattern.matcher(innerString);
    if (matcher.find()) {
    // if it finds a match print it out
    System.out.print("Found: " + innerString);
    // see if there is a gap between prim and bbb *** check index's etc..
    while (innerString.indexOf("prim") < innerString.lastIndexOf("bbb")) {
    // if more check again another occurance
    findInnerMatch(innerString);
    }

  • RegEx, need help with pattern matching

    im going thru a list of Strings...and id like to match some input to it..but the tutorial for regex wont let me find a smaller string within a bigger one if it exists
    for example i have a String "java.sun.com" and i want to find "sun" or "java" or "com" or "jav" or ".co"
    i think the only way regex will work is if i group the entire thing into
    any ideas on how i can manipulate the string into a proper regex pattern so that itll find any of those "searches"
    thanks

    No, that is not correct. A regex can be constructed to return a match on anything you want. A single character, a newline character, a numeric character and any combination of them. There are limitless possibilities for pattern matching.
    See here:
    http://java.sun.com/j2se/1.4.1/docs/api/java/util/regex/Pattern.html
    Any of the patterns may be compiled into a regex for searching using the matcher.
    An alternative is to use the indexOf method of the string class to find what you are looking for.
    Example:
    String myString = "java.sun.com";
    String matchThis = "n.co";
    int patternFoundAtThisIndexPosition = myString.indexof(matchThis);patternFoundAtThisIndexPosition will be 7;
    or simply:
    int index = myString.indexof("sun");index will be 5;

  • Java.util.regex and replacing patterns with function calls

    Hi everyone,
    I'm in terrible need for help.
    Any advice is much appreciated.
    I have the following sentence in a file. The sequence of numbers is actually a
    date in seconds since 1970. I need to identify the 9 or 10 sequence of numbers
    send that to a method that will transate the numbers into a date in a string format.
    Then replace it in the file.
    Here is an example:
    "My name is Peter. Please 1020421277 help me figure this out 108062327. "
    using the following block I can convert it to this
    "My name is Peter. Please | help me figure this out |. "
    [block]
    Pattern p = Pattern.compile("[0-9]{9,10}+");
    Matcher m = p.matcher("");
    String aLine = null;
    while((aLine = in.readLine()) != null) {
    m.reset(aLine);
    String result = m.replaceAll("|");
    out.write(result);
    out.newLine();
    [end block]
    So I need to change the above block so that my sentence looks like this.
    "My name is Peter. Please 05/03/2002 10:21:17 help me figure this out 06/04/1973 17:18:47. "
    The method that converts the numbers into a date is not of a concern because I already have
    the code to do that.
    If anyone has suggestion, please let me know.
    Thanks in advance.
    Peter
    [email protected]

    Never mind, I was able to figure it out....
    Common2 cm = new Common2();
    Pattern p = Pattern.compile("[0-9]{9,10}+");
    Matcher m = p.matcher("");
    m = p.matcher(s1);
    while ((found = m.find())) {
    String replaceStr = m.group();
    System.out.print("\tReplaceString is: " + replaceStr);
    replaceStr = cm.get_date(replaceStr);
    System.out.println("\t\tConverted to: " + replaceStr);
    m.appendReplacement(buf,replaceStr);
    m.appendTail(buf);
    ----------------- The get_date method in Common2 looked like this ------------------------------
    public String get_date(String myString)
    String s;
    long lsecs = Long.parseLong(myString);
    lsecs = lsecs * 1000; // its now milliseconds.
    // Determine default calendar and then the offset to GMT.
    Calendar localCalendar = Calendar.getInstance();
    int offset = localCalendar.get(Calendar.DST_OFFSET) + localCalendar.get
    (Calendar.ZONE_OFFSET);
    // Take the number of milliseconds subtract the gmtoffset
    Date GMTdate = new Date(lsecs - offset);
    // Format date
    Format myformat;
    myformat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a z ");
    s = myformat.format(GMTdate);
    return s;
    Peter

  • Search and replace, with pattern matching using a table

    I need to inspect a data stream and standardise a set of codes. I need to
    1. Match any patterns with a dash character and remove the dash and any following characters, eg BN-S -> BN, BN-SH -> BN, ARG-22 -> ARG, etc.
    2. Make a few specific word for word replacements, eg, PAEDSH -> PAED
    This is easy to hard code but can it be done using a table of regex substitutions? Can anyone give a pointer or link to some example code? The couple of regex replacement examples I've found use regex to locate but hard code substitutions.
    Thanks

    You could store all your patterns in a Map. Then iterate over the map inserting the patterns into a regex.

  • RegEx Problem with flag COMMENTS

    Hello,
    I have the following Exception:
    java.util.regex.PatternSyntaxException: Unclosed group near index 9
    when my program is running with this flags:
    Pattern patt = Pattern.compile("^(@#@.+)$", Pattern.MULTILINE | Pattern.COMMENTS);but when I run this:
    Pattern patt = Pattern.compile("^(@#@.+)$", Pattern.MULTILINE);it works fine.
    Any COMMENTS ;-) for this problem? The entire RegEx is much bigger. I want to comment it.
    Thanks sacrofano

    Hi,
    thanks for your help, but it did not work.I did not suggest anything that would work! I was trying to point out that the Javadoc says that everything from # to the end of the pattern is treated as comment.
    I run this
    Pattern patt =
    Pattern.compile("^(?:(@#@.+))$",(Pattern.COMMENTS));[/
    code]So why, based on reading the Javadoc, would you expect this RE to compile? Everything after the # is treated as comment so your effective regular expression is "^(?:(@" which is obviously an invalid RE!
    with same exception as above.
    Is there a problem with the Flag Pattern.COMMENTSNo! RTFD.

  • ***Need Regex for a pattern

    Hello,
    I need a pattern for the following use cases: I am using Java
    1. var so = nokia.device.load('abc','abc');
    2. var so = nokia.device.load("abc","abc");
    3. var so = nokia.device.load("abc");
    4. var so = nokia.device.load('abc');
    // 5. var so = nokia.device.load('abc'); (Line is commentted)+
    function init()
    if (window.menu) {
    // set tab-navigation mode and hide softkeys
    widget.setNavigationEnabled(false);
    var so = nokia.device.load("abc");(Line is commentted)+
    I need a regex pattern which will be give me only the function statments which are listed in bold and NOT italic format function statements as those statements are commented.
    Basically, the pattern should give me the statments which are not commented.
    Please help me, its urgent.
    Thanks,
    Mallikarjun.
    Edited by: arjun2010 on Apr 26, 2010 9:36 PM

    I'll let the fact that the requirement is very dodgy slide for a moment. It seems that a pattern might not be the solution here; why not do something like the following:
    SWEEP 1:
    - scan through the code one character at a time, looking for comment blocks and comment lines.
    - remove all comment blocks from the code (or rather, copy all parts that are not comments to a new buffer)
    now you have code cleaned of all comments
    SWEEP 2:
    - scan for 'noka.device.load' and extract those pieces of code with some clever string comparisons.
    Of course I don't know the why behind this requirement, but if I had to implement such a crude requirement I'd do it as simple as possible in stead of as clean as possible.

Maybe you are looking for