Regular expressions string length

Hi
New to regular expressions and trying to create an expressions that will test if a string does not contain any number and is less than 20 characters long! This works for determining if it has any numbers in it, but how do I specify that it can be between 1 and 20 characters in length? The + means >1 but how do I cap it?
Pattern p = Pattern.compile("[a-zA-Z]+");
         Matcher m = p.matcher(value);
         if (m.matches()) System.out.println("yes");I have tried [a-zA-Z]+{5} but that doesn't work. Any handy hints... can't find much stuff that is applicable via google, frustrating.
Thanks.

Looce wrote:
Pattern p = Pattern.compile("[a-zA-Z]{1,20}"); // repetition totally replaces +, doesn't coexist with it
Matcher m = p.matcher(value);
if (m.matches()) System.out.println("yes");
Note that the following code can be shortened by doing:
if(value.matches("[a-zA-Z]{1,20}")) { /* ... */ }

Similar Messages

  • Regular Expression string

    Hi,
    I'm looking for a single regular expression.
    E.g. My string is 'get data for comparison'. So when using regular expression as \Wcompar then it returns true.
    But I dont want it to return true for string 'get data for comparable' with the same regular epression.
    Here, I do not want string comparable and rest all the forms of compar to be selected.

    It's not really clear what you need, perhaps something like this?
    -- data:
    with t as
    select 'get data for comparison' txt from dual union all
    select 'get date for compar xxxxx' txt from dual union all
    select 'compar xx' txt from dual union all
    select 'compare xx' txt from dual union all
    select 'xx compar' txt from dual union all
    select 'xx compare' txt from dual
    -- query:
    select txt from t
    where regexp_like(txt,'(\W|^)compar(\W|$)');
    TXT
    get date for compar xxxxx
    compar xx
    xx compar(\W|^) means word-limit or start of the string
    (\W|$) means word-limit or end of the string
    Edited by: hm on 21.12.2011 05:29

  • Command line style regular expression string parser

    Hi people,
    I am currently working on a program where I need to parse a file (or any input stream) line by line. I then need to parse every line for arguments. Each line is formatted similar to how arguments are passed to the command line. The regular expression needs to split every line by any encountered whitespace, but needs to be able to retain any whitespace within double quotes (i.e. "some spaced text here"). Arguments can be numbers, booleans and (quoted) strings. Quoted strings must also be able to have escaped quotes in it (as below). The quotes for the quoted string (the outer ones, obviously not the escaped ones) do not necessarily have to be retained.
    An example input line:
    arg1 arg2 "arg 3" "arg 4" 987 arg6 "arg \"arg \"arg 7"
    Desired example output:
    arg1
    arg2
    arg 3
    arg 4
    987
    arg6
    arg "arg "arg 7
    After the input line has been split up the program will handle any parsing (i.e. numbers, booleans, etc.). The program currently uses a simple for loop to iterate over all characters in the line and splits it up appropriately by checking every character. However, if this can be done automatically by using a regular expression passed to String.split() (or with some use of the regex package), it would remove quite a bit of redunant code and make the program that much more maintainable.
    I do not have much experience with regular expressions since I have never really had the need to use them, but if they can work in this case it would be great.
    Thanks in advance for any help.

    Almost any parsing problem can be solved if you throw a big enough and ugly enough regex at it, or so I'm told.
    I think what you are doing is also amenable to java.io.StreamTokenizer:
    import java.io.*;
    import static java.io.StreamTokenizer.*;
    public class StreamTokenizerExample {
        public static void main(String[] args) throws IOException {
            StringReader input = new StringReader("arg1 arg2 \"arg 3\" \"arg 4\" 987 arg6 \"arg \\\"arg\\\" arg 7\"\nnextline");
            StreamTokenizer in = new StreamTokenizer(input);
            in.eolIsSignificant(true);
            for(int ttype; (ttype = in.nextToken()) != TT_EOF; ) {
                switch (ttype) {
                    case TT_WORD:
                        System.out.println("String[" + in.sval + "]");
                        break;
                    case TT_NUMBER:
                        System.out.println("number[" + in.nval + "]");
                        break;
                    case TT_EOL:
                        System.out.println("[EOL]");
                        break;
                    case '"':
                        System.out.println("quoted[" + in.sval + "]");
                        break;
                    default:
                        System.out.println("unexpected " + ttype);
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Regular Expression / String matching other than equality check with groovy.

    I want to have a string comparison operation using a groovy expression.
    Not an equality check, but something like
    #{variableName like 'IC%'?'true':'false'}
    I saw some operators like
    #{bindings.gradeName.inputValue =~ 'IC'?true:false}
    But it doesnt seem to be working.
    Is it possible with groovy?
    Arun

    Hi
    nything will do.
    And not using bean.
    This expression has to added in an AMX page (ADF Mobile
    It depends on where you want to execute this. Groovy in a validation script would be different to EL in a page as they would be in different stages in the lifecycle.
    Now for ADF MObile this may be different, I dont know.'
    If its to be part of a validation then you can call the source methods in groovy and do the comparison.
    from a validator for instance:
    source.getGradeName() returns the grade name before commiting.
    String enteredgrade = source.getGradeName();
    if (enteredgrade.index(0).equals('I') and enteredgrade(1).equals('C'){
    do what you want here. i.e. return true or false etc.
    el in a page would look entirly different but you can implement this same functionality in a bean, access it via the accessors and then return true or false.
    if you are already using EL and you managed to link your page with JSTL, you will have to define the access variable in the header section inorder to access it and then use "startswith", though I havent tried it this way.

  • Regular Expressions / String Match

    Hi Everyone,
    thankx for reading this
    I'm programing a oracle form which at one part read's the full path into a file (a text file) and place's it on a VARCHAR2 field. This is the path into the file and not the file data.
    I would like to match this string (the file path) to a another one (in order to know if the file name respect some rules). This is a very easy thing to do under Perl / PHP and other languages. But how can i do this under PL/SQL ?
    I have search but failed to find any clue.
    Any pointers would be great, or a small example
    Thankx Stay Happy
    Miguel Angelo

    Hi,
    you can use INSTR and SUBSTR for String comparison
    INSTR(char1,char2) shows you the first occurence of char2 in char1
    INSTR(char1,char2,n,m)
    shows the m'th occurence of char2 in char1 starting on n
    Frank

  • Regular Expression / String question?

    Ok, So I want to do a String.split and split by a
    (.*)But since parenthese's are regex, how would I search for that without messing up the call?

    CButz wrote:
    so
    \(.*\)should work?Yup.
    But note that if the regex is Java string literal--that is, in your source code in double quotes, as opposed to being read from user input or a config file, you'll need to double the backslash.
    "\\(.*\\)"Also, note that that regex will match (abc)def(ghi) as one group. The abc)def(ghi will match the .*

  • Regular Expression to capture user's input string

    I am writing a helper class to split user input string into String array according to the following pattern:
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class TestDelimiter {
    static Pattern p = Pattern.compile("(.*?)[,;]{1}");
    static Matcher m;
        public static void main(String[] args) {
            String input = "AAA111111,BBB222222;CCC333333";
            m = p.matcher(input);
            while(m.find()){
                String output = m.group(1);
                System.out.println(output);
    }Output:
    AAA111111
    BBB222222My question is, how can I modify the regular expression string so that the CCC333333 (last element) can also be included?

    roamer wrote:
    Ok, let's don't argue on this point.Who's arguing?
    I think I got the answer. For simplicity, I can just manually add a ";" or "," string after each user input. Just like:You never said anything about that before. You asked how to split "AAA111,BBB222;CCC333" into its components and you were given a correct answer.
    Maybe you should rephrase your question including this added requirement. Do you need to have the separator included in the final outputs or why do you want to suddenly add things to user input?

  • Regular expression for 2nd occurance of a substring in a string

    Hi,
    1)
    i want to find the second occurrence of a substring in a string with regular expression so that i can modify that only.
    Ex: i have a string like ---> axe,afn,sdk,jdi,afn,mki,mki
    in this i want the second occurance of afn and change that one only...
    which regular expression i have to use...
    Note that ...i have to use regular expression only....no string manipulation methods...(strictly)
    2)
    How can i apply the multiple regular expressions multiple times on a single string ..i.e in the above instance i have to apply the same 2nd occurrence logic for
    substring mki also. for this i have to use a single regular expression string that contains validations for both the sub strings mki and afn.
    Thanks in advance,
    Venkat

    javafreak666 wrote:
    Hi,
    1)
    i want to find the second occurrence of a substring in a string with regular expression so that i can modify that only.
    Ex: i have a string like ---> axe,afn,sdk,jdi,afn,mki,mki
    in this i want the second occurance of afn and change that one only...
    which regular expression i have to use...
    Note that ...i have to use regular expression only....no string manipulation methods...(strictly)
    2)
    How can i apply the multiple regular expressions multiple times on a single string ..i.e in the above instance i have to apply the same 2nd occurrence logic for
    substring mki also. for this i have to use a single regular expression string that contains validations for both the sub strings mki and afn.
    Thanks in advance,
    VenkatWhat do you mean by using a regex to get the index of a second substring? There is not method in Java which uses regex to et the index of a substring.
    There are various indexOf(...) methods for this:
    String text = "axe,afn,sdk,jdi,afn,mki,mki";
    String target = "afn";
    int second = text.indexOf(target, text.indexOf(target)+1);
    System.out.println("second="+second);Of course you can find the index of a group like this:
    Matcher m = Pattern.compile(target+".*?("+target+")").matcher(text);
    System.out.println(m.find() ? "index="+m.start(1) : "nothing found");but there is not single method that handles this: you'll have to call the find() and then the start(...) method on the Matcher instance, so the indexOf(...) approach is the favourable one, IMO.

  • Pattern matching regular expressions

    I'm attempting to determine if a string matches a pattern of containing less than 100 alphanumeric characters a-z or 0-9 case insensitive. So my regular expression string looks like:
    "^[a-zA-Z0-9]{0,100}$"And I use something like...
    Pattern pattern = Pattern.compile( regexString );I'd like to modify my regex string to include the email 'at' symbol "@". So that the at symbol will be allowed. But my understanding of regex is very limited. How do I include an "or at symbol" in my regex expression?
    Thanks for your help.

    * Code by sabre150
    private static final Pattern emailMatcher;
        static
            // Build up the regular expression according to RFC821
            // http://www.ietf.org/rfc/rfc0821.txt
            // <x> ::= any one of the 128 ASCII characters (no exceptions)
            String x_ = "\u0000-\u007f";
            // <special> ::= "<" | ">" | "(" | ")" | "[" | "]" | "\" | "."
            //              | "," | ";" | ":" | "@"  """ | the control
            //              characters (ASCII codes 0 through 31 inclusive and
            //              127)
            String special_ = "<>()\\[\\]\\\\\\.,;:@\"\u0000-\u001f\u007f";
            // <c> ::= any one of the 128 ASCII characters, but not any
            //             <special> or <SP>
            String c_ = "[" + x_ + "&&" + "[^" + special_ + "]&&[^ ]]";
            // <char> ::= <c> | "\" <x>
            String char_ = "(?:" + c_ + "|\\\\[" + x_ + "])";
            // <string> ::= <char> | <char> <string>
            String string_ = char_ + "+";
            // <dot-string> ::= <string> | <string> "." <dot-string>
            String dot_string_ = string_ + "(?:\\." + string_ + ")*";
            // <q> ::= any one of the 128 ASCII characters except <CR>,
            //               <LF>, quote ("), or backslash (\)
            String q_ = "["+x_+"$$[^\r\n\"\\\\]]";
            // <qtext> ::=  "\" <x> | "\" <x> <qtext> | <q> | <q> <qtext>
            String qtext_ = "(?:\\\\[" + x_ + "]|" + q_ + ")+";
            // <quoted-string> ::=  """ <qtext> """
            String quoted_string_ = "\"" + qtext_ + "\"";
            // <local-part> ::= <dot-string> | <quoted-string>
            String local_part_ = "(?:(?:" + dot_string_ + ")|(?:" + quoted_string_ + "))";
            // <a> ::= any one of the 52 alphabetic characters A through Z
            //              in upper case and a through z in lower case
            String a_ = "[a-zA-Z]";
            // <d> ::= any one of the ten digits 0 through 9
            String d_ = "[0-9]";
            // <let-dig> ::= <a> | <d>
            String let_dig_ = "[" + a_ + d_ + "]";
            // <let-dig-hyp> ::= <a> | <d> | "-"
            String let_dig_hyp_ = "[-" + a_ + d_ + "]";
            // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
            // String ldh_str_ = let_dig_hyp_ + "+";
            // RFC821 looks wrong since the production "<name> ::= <a> <ldh-str> <let-dig>"
            // forces a name to have at least 3 characters and country codes such as
            // uk,ca etc would be illegal! I shall change this to make the
            // second term of <name> optional by make a zero length ldh-str allowable.
            String ldh_str_ = let_dig_hyp_ + "*";
            // <name> ::= <a> <ldh-str> <let-dig>
            String name_ = "(?:" + a_ + ldh_str_ + let_dig_ + ")";
            // <number> ::= <d> | <d> <number>
            String number_ = d_ + "+";
            // <snum> ::= one, two, or three digits representing a decimal
            //              integer value in the range 0 through 255
            String snum_ = "(?:[01]?[0-9]{2}|2[0-4][0-9]|25[0-5])";
            // <dotnum> ::= <snum> "." <snum> "." <snum> "." <snum>
            String dotnum_ = snum_ + "(?:\\." + snum_ + "){3}"; // + Dotted quad
            // <element> ::= <name> | "#" <number> | "[" <dotnum> "]"
            String element_ = "(?:" + name_ + "|#" + number_ + "|\\[" + dotnum_ + "\\])";
            // <domain> ::=  <element> | <element> "." <domain>
            String domain_ = element_ + "(?:\\." + element_ + ")*";
            // <mailbox> ::= <local-part> "@" <domain>
            String mailbox_ = local_part_ + "@" + domain_;
            emailMatcher = Pattern.compile(mailbox_);
            System.out.println("Email address regex = " + emailMatcher);
        }Wow. Sheesh, sabre150 that's pretty impressive. I like it for two reasons. First it avoids some false negatives that I would have gotten using the regex I mentioned. Like, [email protected] is a valid email address which my regex pattern has rejected and yours accepts. It's unusual but it's valid. And second I like the way you have compartmentalized each rule so that changes, if any custom changes are desired, are easier to make. Like if I want to specifically aim for a particular domain for whatever reason. And you've commented it so that it is easier to read, for someone like myself who knows almost nothing about regex.
    Thanks, Good stuff!

  • How to define a regular expression using  regular expressions

    Hi,
    I am looking for some regular expression pattern which will identify a regular expression.
    Also, is it possible to know how does the compile method of Pattern class in java.util.regex package work when it is given a String containing a regex. ie. is there any mechanism to validate regular expression using regular expression pattern.
    Regards,
    Abhisek

    I am looking for some regular expression pattern which will identify a regular
    expression. Also, is it possible to know how does the compile method of
    Pattern class in java.util.regex package work when it is given a String
    containing a regex. ie. is there any mechanism to validate regular
    expression using regular expression pattern.It is impossble to recognize an (in)valid regular expression string using a
    regular expression. Google for 'pumping lemma' for a formal proof.
    kind regards,
    Jos

  • Looping through files with Regular expressions ?

    Hi,
    My Question is:
    if i have the following Regular Expression,
    String regrex = "tree\\s\\w{1,4}.+\\s=\\s(.*;)";
    The file in which i am looking for the string has multiple entries, is it
    possible to do another regular expression on the captured group (.*;)
    which is in the original Regular expression ?
    The text that is captured by the RE is of the type "(1,(2,((3,5),4)));" for
    each entry, and different entries in the file have slightly different syntax
    is it possible to loop through the file and first of all check for the presence
    of the original RE in each entry of the file
    and then secondly, check for the presence of another RE on the captured group?
    [ e.g. to check for something like, if the captured group has a 1 followed by a 3
    followed by a 5 followed by a and so on ].
    Thanks Very much for any help, i've been struggling with this for a while!!
    Much appreciated
    The code that i have so far is as follows:
    import java.util.*;
    import java.util.regex.*;
    import java.io.*;
    import java.lang.*;
    import javax.swing.*;
    public class ExpressReg {
    public String Edit;
    public ExpressReg(String editorEx){
    Edit = editorEx; // Edit = JTextArea
    String regrex = "tree\\s\\w{1,4}.+\\s=\\s(.*;)";
    //String regrex1 = "(.*;)";
    Pattern p = Pattern.compile(regrex);
    Matcher m = p.matcher(editorEx); // matcher can have more than one argument!
    boolean result = m.find();
    if(result){                           
    JOptionPane.showMessageDialog(null, "String Present in Editor");
    else if(!result){
    JOptionPane.showMessageDialog(null, "String Not Present In Editor");

    if i have the following Regular Expression,
    String regrex = "tree\\s\\w{1,4}.+\\s=\\s(.*;)";
    The file in which i am looking for the string has multiple entries, is it
    possible to do another regular expression on the captured group (.*;)
    which is in the original Regular expression ?Yes, the capturing group is $1 (the only one) referenced in source code as m.group(1).
    m.group() will return entire matching.
    simply use this way:
    String result = m.group(1);
    // your stuff: could be another validation
    The text that is captured by the RE is of the type "(1,(2,((3,5),4)));" for
    each entry, and different entries in the file have slightly different syntax
    is it possible to loop through the file and first of all check for the presence
    of the original RE in each entry of the file
    and then secondly, check for the presence of another RE on the captured group?Again "Yes", no limits!
    Don't need to create another Matcher, just use m.reset(anotherSourceString)..loop using the same pattern.
    Note: Take care with ".*" because regex nature is "greedy", be more specific, eg.: "\\d" just matches digits (0-9).
    Can you give us some sample of "slight difference" ?

  • Regular Expressions - replace inner group

    I'm trying to do the following:
    1. Given the following string:
    Truth, like tumors, require a cut to be removed.
    2. Grab the whole sentence and the following:
    like tumors
    3. Replace "like tumors" with "like posion" and add one line to the sentence like so:
    Truth, like posion, require a cut to be removed.
    To be free you must endure pain for a season to finally be free from it.
    I can grab the sentence with reg expressions, I can even grab the second search (#2) in a group, I'm just wondering if there is an elegant way to replace both at the same time. I could always replace one then search and replace the next, but that seems redundant since I can grab both the first time around. Any help?

    according to:
    http://javaalmanac.com/egs/java.util.regex/GroupInRep.html?l=find
    // Compile regular expression
    String patternStr = "\\((\\w+)\\)";
    String replaceStr = "<$1>";
    Pattern pattern = Pattern.compile(patternStr);
    // Replace all (\w+) with <$1>
    CharSequence inputStr = "a (b c) d (ef) g";
    Matcher matcher = pattern.matcher(inputStr);
    String output = matcher.replaceAll(replaceStr);
    // a (b c) d <ef> gthis should be exactly what you're looking for.

  • JAVA regular Expression problem

    i have a string AS FOLLOWS-
    "N\E'\ERAJ";
    u can create this string as --- > String str="N\\E'\\ERAJ "
    i want output as below--
    N\\E\'\\ERAJ
    don't us the looping.
    Thanks in advance.
    nJoy the Regular Expression.

    String myString = myString.replaceAll("\","\\");No. To merely double all backslashes, you would use  myString = myString.replaceAll("\\\\", "\\\\\\\\");But it looks like the OP wants to escape apostrophes as well:  myString = myString.replaceAll("(['\\\\])", "\\\\$1");...or possibly all punctuation characters:  myString = myString.replaceAll("(\\p{Punct})", "\\\\$1");

  • Regular expression for html links

    Hi, I'm trying to get text/link pairs from a string, accepted links
    are like:
    text1
    text2
    The expected result would be:
    url: url1
    Text: text1
    url: url2
    Text: text2
    I use the following regular expression to catch the texts and the urls:
    "<a href=\"*(.*)\"*.*>(.*)</a>"
    group(1) should be the url and group(2) the text.
    But it doesn't work ok, I got something like:
    url: http://url1/" garbagetags
    text: text1
    url: utl2
    text: text2
    I'm trying to avoid links with " and without it and dinamic html
    tags.
    I think the problem is the Regular Expression string, I'm new using
    them and I can't found the right one, if you know what's wrong with
    my R.E. string, please help me.!
    thanx

    Had to break it in to two regular expressions:
    import java.util.regex.*;
    class B2  {
       public static void main(String[] args) {
            //String INPUT = "<a href=\"http://url1/\" garbagetags>text1</a>";
            //String INPUT = "<a href=url2>text2</a>";
            //String INPUT ="<a href=\"http://www.google.com\">Google search engine</a>";
              String INPUT="<a id=1a class=q href=\"/imghp?hl=en&tab=wi&ie=UTF-8&oe=UTF-8\" onClick=\"return c('www.google.com/imghp','wi',event);\"><font size=-1>Images</font></a>";
            //String REGEX = "<a .*href=\\\"?h?t?t?p?:?/?/?([\\w\\.\\?\\&=\\-\\d]*)/?\\\"?.*>(.*)</a>";
            String REGEX = "<a .*href=\\\"?h?t?t?p?:?/?/?([\\w\\.\\?\\&=\\-\\d]*)/?\\\"?.*>";
            String REGEX2 = ">\\b([\\w\\s\\d]+)\\b<";
            Pattern p = Pattern.compile(REGEX);
            Matcher m = p.matcher(INPUT);
            StringBuffer sb = new StringBuffer();
            if ( m.find() ) {
            System.out.println(m.group(1) + "     " );  }
            else { System.out.println("No MAtch found");  }
            Pattern p2 = Pattern.compile(REGEX2);
            Matcher m2 = p2.matcher(INPUT);
            if ( m2.find() ) {
            System.out.println(m2.group(1) + "     " );  }
            else { System.out.println("No MAtch found");  }
    } You do realize that you'll never get 100% accuracy with this. There are too many possible variations to account for them all.

  • Regular Expression Technique in ColdFusion

    I'm new to Coldfusion and I've never really used regular expressions before.  How would I write a ColdFusion function (or just a conditional statement) to check if a form variable is a match for an IP network (44.42.94.0/18)?
    I'm just basically looking to see if the backslash "/" character is in the string.

    There are actually plenty of well-developed regular expression strings available on the Internet, which you can simply "copy and use."  You don't have to spend too much time figuring-out the correct pattern of chicken scratches.
    It's not quite as convenient as saying  "use Regexp::Common::URL;" but one cannot have everything in "less-enlightened" languages like CF...
    You do need to understand them, however.  When you look at the string given in a previous reply, you do need to understand the meaning of all those symbols, and you need to practice the art of being able to cook them up extemporaneously.

Maybe you are looking for