Java regex doubt?

I have a string by as follows:
String name = "aaaaaaaaaahgcnjcdcd";I am trying to validate the above string. When the number of "a" in the string excceds 5 and above, I need to throw an error. I tried as follos:
if (name.matches("A{5,}")){
system.out.println("There is an error");
}The above code works only if my name is "aaaaaaaaaaaa" (contains only more than 5 "a"s)and it is not working when name is like "aaaaaaaaaahgcnjcdcd". Can anyone give suggestion so that I will be able to thrw an error if there are more than 5 continous "a" s along with other charactes as "aaaaaaaaaahgcnjcdcd".

cotton.m wrote:
For the regex way you need optional wildcards on either side. And sabre or uncle_alice are likely to yell at me for suggesting indexOf so maybe just do that instead.Far from it. If all the OP is interested in is a run of 5 or more 'a' chars then indexOf() is perfect BUT if he wants 5 or more of run of any of a possible set or chars then regex fits the problem much better. Something like
boolean isValid = "your string xxxxx possibly containing 5 or more of a sequence of x,y or z".matches(".*([xyz])\\1{4,}.*");it is possible to refine this so that there is much less backtracking but until I better understand the OP's requirement ...

Similar Messages

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

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

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

  • 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

  • Java Regex Pipe Delimited ?

    Hello
    I am trying to split the string which is pipe delimited. I am new to Regex and new to Java.
    My Java/Regex code line to split is:
    listColumns = aLine.split("\\|"); // my code has 2 backslash-escapes chars plus 1 pipe char but this forum does not allow me to put pipes or escapes correctly and plain text help is of NO HELP 8^(
    My input string has 3 leading and 4 trailing pipe characters
    My Output from split: (3 leading emptry strings work but 4 trailing pipe delimiters dont work)
    SplitStrings2:[]
    SplitStrings2:[]
    SplitStrings2:[]
    SplitStrings2:[col1]
    SplitStrings2:[col3]
    SplitStrings2:[col4]
    I do get 3 empty strings for all 3 leading pipes but no empty strings for the any traling 4 pipe characters.
    What do I need to change the code such that all repeated pipes resulted in same number of empty strings returned by split method?
    thanks
    YuriB
    Edited by: yurib on Nov 28, 2012 12:25 PM
    Edited by: yurib on Nov 28, 2012 12:25 PM
    Edited by: yurib on Nov 28, 2012 12:29 PM

    1. The pipe is a meta-character so escape it.
    2. Split rolls things up for you unless you tell it otherwise.
    String s = "|||A|B|C||||";
    String[] array = s.split("[|]", 10);
    for(int i=0; i < array.length; i++)
         System.out.println("" + i + ": " + array);

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

  • Sed rules to java regex

    Hi,
    what is the connection between sed regex rules and java regex rule. Is there an easy way to convert sed to java? or do i have to learn sed?....
    Thanks

    IIRC, Java regex rules are like Perl's (although the syntax for invocation differs a bit), and Perl's are basically a superset of sed's, except there's a difference with parentheses. In Perl/Java, parentheses always group and you have to backslash-quote them to make them interpreted as plain parenthesis characters, whereas in sed, you backslash-quote them to make them be interpreted as grouping indicators.
    Why? What problem are you having?

  • 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

  • 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

  • Where do i post java script doubts?

    Where do i post java script doubts?

    JavaScript has nothing to with Java at all, so if you are searching for a sub-forum of this forum to post JavaScript questions then I can't help you.
    You will need to google for a JavaScript forum, maybe someone around here knows of a good one.

  • 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

  • JAVA-Maping Doubts--Urgetn

    Hi Frnds,
    i am working on JAVA Mapping, recently i started but when i started working i have some issues...
    1)With out main method how to execute JAVA Mapping, i got one link  i am trying to implement the scenario,i am terying to comile java code but its not compiling , bcz no main method, how executeJAVA Mapping.
    2) Whats the use of Stream Transformation interface.
    3) whats the use of Mapping Trace,Abstarct Trace.
    Please solve my above doubts...
    Regards,
    Raja Sekhar
    please

    Hi,
    The runtime environment for Java mappings has an mapping API. To use Java mapping, you must define a Java class that implements the Java interface com.sap.aii.mapping.api.StreamTransformation. This interface has two methods:
    public void execute(java.io.InputStream in, java.io.OutputStream out)
    At runtime, the Integration Engine calls this method to execute a mapping. This method contains an input stream for the source document and an output stream for the target document as parameters. These streams are usually XML documents. You can import the substructures to be converted from the input stream and output the converted target document in the output stream.
    ●     public void setParameter(java.util.Map param)
    The Integration Engine transfers parameters to the mapping program with this method. It evaluates these parameters at runtime in the method execute(). This enables you to control the process flow of the mapping.
    The transferred object that implements the Java interface java.util.Map contains seven key/value pairs as parameters. These correspond to corresponding fields in the message header. Apart from the MAPPING_TRACE constant, the value objects are of type java.lang.String. The key objects are defined in the class com.sap.aii.mapping.api.StreamTransformationConstants
    for more info
    http://help.sap.com/saphelp_nw04/helpdata/en/a4/64b93d0d4e6b3be10000000a114084/frameset.htm

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

Maybe you are looking for

  • Error at the time of billing due list

    Dear SD gurus, I have created  a sales order with  1 line item and order quantity as 20.With reference to this order I have created two deliveries each of 10 qty.I am trying to invoice both the deliveries by using VF04(Billing due list), I am able to

  • Error: Web service object exists

    Hi all! I am very new with SAP Web Services so, to learn, I created a very simple function, enabled it for RFC, and activated and successfully tested it. After that, I tried to create a Service, starting the Wizard (Utilities > More utilities > Creat

  • SIDnn disabled on Production during Startup of Development Instance

    Hello, i've got  a problem with our SAP environment, after restarting an instance yesterday evening on the dev LPAR the SIDnn user on the production LPAR was automatically disabled?! Is this a password issue? Because I've got another problem with the

  • Can you embed HTML code into a Captivate project?

    Hi there. Is it possible to embed HTML code into a project? I can't find any options to do it. I'm using Captivate 7. Thanks.

  • From one viewpoint to another via a third viewpoint

    Hi! I need help to make a function/script, on a button, that takes me from one viewpoint to another via a third viewpoint. I want it to be like this: When I push a button I want to change from view1 to view2 but before the camera goes to view2 it wil