Pattern regex question

What kind of pattern would i use for representing all the different java syntax words... such as void, class, public, static... and so on.
And is there anyway to specifty things such as variables, class names, method names through pattern matching?
For example, suppose i want to make a pattern for variable names in java code. How would that regexp look?
For content text it would look like (i guess):
p = Pattern.compile("\\b\\w+");

p = Pattern.compile("(void|class|import|this|true|false|boolean|int|float|new)");
          set = new SimpleAttributeSet();
          StyleConstants.setForeground(set, Color.BLUE);
          StyleConstants.setBold(set, false);
          patterns.addElement(new RegExStyle(p, set));That fixes all those words at least.

Similar Messages

  • Patterns/regex: determine an intersection of patterns/regex

    Hi.
    Does anyone know how to determine the pattern/regex that reflects the intersection of 2 or more patterns?
    F.ex.:
    intersection of [0-9]+[a-z]+ with [1-2]*[a-c]* would be [1-2]+[a-c]+ right?
    Any ideea?
    Many thanks.

    Wow! That was quick.
    I also think that it's not so easy to do. But the hope never dies ... I thought someone already got this problem and knows the solution...
    Anyway, thanks for your response.
    P.S. the example was just an example to explain what i mean. I had no doubts that's right.

  • 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 = ".*?(<[^<>]*(?:<.*?>)*.*?>).*";

  • 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

  • Pattern fill question

    Hi i'm a student and learning how to work with with photoshop, indesign and illustrator. I've only been practesing for a month and a half now but we al had to start somewhere
    Now my question is: i've been trying to get a pattern fill in illustrator with simple circle shapes. This, i can do. But then i want to put the pattern in an object without it cutting the edge of the object so i don't get any circles cut in half.
    So that is looks like the shape is made from these tiny shapes.
    I'm probably not making any sense so here's an example that kinda looks like my idea: http://us.123rf.com/400wm/400/400/princesszelda/princesszelda1006/princesszelda100600005/7 219623-heart-shape-made-of-circles-inspired-by-colour-blind-tests-the-vector-version-has-t he-heart-and-main.jpg
    But without the different colours ofcourse.
    Thanks for answering in advance, i've been stuck with the for days

    The example is probably not a pattern fill. Notice how the circles align with the border of the shapes. This would not be possible using a pattern fill. It MAY be possible using the "Symbol Sprayer" tool or "Scatter Brush". You might want to study these features.

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

  • Pattern regex matching advice needed

    Hi All,
    Many thanks for any/all advice :)
    Here's my problem. I'm trying to scan a text file for...
    \foo(parm1|parm2)
    ...in which I want the sub-string "parm1|parm2"
    So... [\\]foo matches the first section. No problem...
    It's when I try adding the '(' or ')' that I'm getting errors.
    java.util.regex.PatternSyntaxException: Unclosed character class near index
    [\]foo(.*)
    Basically, I'm trying to create a pattern, which can recognize \foo(parms), and extract the parms sections.
    Any ideas?

    Yes you can do this. It is not allowed in basic java but there are always around the syntax rules. What you can do it use AspectJ plugin in for eclipse and define a cutpoint and make it extend from two classes. What it does is it parses the byte code and inputs the code directly into the byte code. It's pretty neat.
    A simplier approach would be to have two classes A and B. Have A extend BASE and then have B Extend A and then therefore B "isa" A and a BASE.
    Hope this helps.

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

  • 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: question about finding Overlapping matches using regular expressions

    I have the following problem.
    Say for my pattern I use:
    Pattern pattern = Pattern.compile("AAA");
    Matcher matcher = pattern.matcher("AAAAAA");when I run a loop
    while (matcher.find())
    System.out.println("Match Found: "+matcher.start()+" "+matcher.end());I get 2 Hits shown in the following output:
    Match Found: 0 3
    Match Found: 3 6
    therefore the regex is seeing the first AAA then the second AAA.
    I want it to find the other AAA's in there that are overlapping the other two finds i.e. I want the output to find
    AAA from 0 to 3
    AAA from 1 to 4
    AAA from 2 to 5 and finally
    AAA from 3 to 6
    thereby including the overlapping finds.
    How can I do this using regex? what am I missing that prevents the overlapping matches to be found? Do I need a quantifier?
    Thanks for the help!

    While the solutions above work fine with the given input, they don't really find all overlapping matches. They just find the longest possible match at each start position. Here's a more thorough approach:import java.util.*;
    import java.util.regex.*;
    public class Test
      public static List<String> matchAllWays(String rgx, String str)
        Pattern p = Pattern.compile(rgx);
        Matcher m = p.matcher(str);
        List<String> result = new ArrayList<String>();
        int len = str.length();
        int start = 0;
        int end = len;
        while (start < len && m.region(start, len).find())
          start = m.start();
          do
            result.add(m.group());
            end = m.end() - 1;
          } while (end > start && m.region(start, end).find());
          start++;
        return result;
      public static void main(String[] args)
        List<String> matches = matchAllWays("a.*a", "abracadabra");
        System.out.println(matches);
    }This approach requires JDK 1.5 or later; that's when the regions API was added to Matcher.

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

  • Cfform and regex question

    I'm trying to make sure that a email address is in the
    correct format, using
    this regex:
    <cfinput type="text" name="contactEmail" id="contactEmail"
    validate="regular_expression"
    pattern="^([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.
    (([a-z]{2,3})|(aero|coop|info|museum|name)))?$"
    message="Email is not in
    correct format.">
    When the form is submitted, it still processes a incorrectly
    formed email
    address without a complaint.....

    > <cfinput type="text" name="contactEmail"
    id="contactEmail"
    > validate="regular_expression"
    >
    pattern="^([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.
    > (([a-z]{2,3})|(aero|coop|info|museum|name)))?$"
    message="Email is not in
    > correct format.">
    >
    > When the form is submitted, it still processes a
    incorrectly formed email
    > address without a complaint.....
    What examples of incorrectly-formed email addresses is it
    accepting? I can
    think of a number of perfectly valid patterns that one will
    reject, too.
    To be frank, attempting to validate an internet email address
    (as per RFC
    2822) is a fool's errand. You could possibly validate the
    domain name
    part, but the local part can pretty much be anything one
    likes, anyhow. So
    on the LHS of the @ symbol, there's no pattern to validate.
    And what about this sort of thing:
    [email protected]
    Are you going to check that the domain is actually registered
    and active,
    and has an SMTP server receiving email? No, didn't think so.
    So what's
    the point?
    I can understand forcing a person to enter SOMETHING as an
    email address,
    and maybe type it in twice so as to minimise the chance of
    typos, but if
    they don't want to give you an email address, they won't.
    If you want to force a person to enter a VALID email address,
    then make
    sure part of their registration is done via responding to an
    email to their
    designated address...
    Adam

  • Route Pattern Add Question

    CUCM 9.1.2
    I am trying to get a better understanding of what happens when you add a Route Pattern. When you click save a warning pops up saying
    "Any update to this Route Pattern automatically resets the associated gateway or route list."
    This pattern is tied to a route list which is then tied to the gateway. What exactly is reset? Will this effect any current calls? How long does this reset take?
    Thanks,
    Alex

    If your route patterns point to route list nothing will be affected, if you point your RP directly to GW or trunk, depending on what is connected to the GW (trunk type) calls may be interrupted. Since you should never point RPs to trunk/GW directly, this is atypically not an issue.
    HTH,
    Chris

Maybe you are looking for

  • How to get all checked items from TreeView in VC++ mfc

    void CPDlg::OnTreeClk(NMHDR *pNMHDR, LRESULT *pResult) NMTREEVIEW& nm = *(LPNMTREEVIEW)pNMHDR; // which item was selected? HTREEITEM hItem = m_columnTree.GetTreeCtrl().GetSelectedItem(); temp = m_columnTree.GetItemText(hItem, 0); MessageBox(temp); if

  • IOTs and primary keys

    hi, I am reading chapter 10 of expert oracle database architecture by tom kyte, and I am getting a little confused. It seems to me as if he is saying that an IOT should be built using the PK of that table. What if our table does not have a PK? thanks

  • HT204053 what is security code for payment card

    what is itune gift cards code?

  • Acrobat logo replaced with windows logo after upgrade to V9

    I have upgraded to Acrobat 9 today from Acrobat 6 pro.  The logos on all pdf files were replaced with the windows logo.  The new module is working but the logos are gone.  Any help will be appreciated. Francis

  • Performance Tuning / RAC

    Hi, does anybody know recommendable docs, study guides or books covering Performance Tuning or RAC for database 11g. Thanks in advance. Uli