Problem with Regular Expression

Hi There!!
I have a problem with regular expression. I want to validate that one word and second word are same. For that I have written a regex
Pattern p=Pattern.compile("([a-z][a-zA-Z]*)\\s\1");
Matcher m=p.matcher("nikhil nikhil");
boolean t=m.matches();
if (t)
          System.out.println("There is a match");
     else
          System.out.println("There is no match");
The result I am getting is always "There is no match
Your timely help will be much appreciated.
Regards

Ram wrote:
ErasP wrote:
You are missing a backward slash in the regex
Pattern p = Pattern.compile("([a-z][a-zA-Z]*)\\s\\1");
But this will fail in this case.
Matcher m = p.matcher("Nikhil Nikhil");It is the reason for that *[a-z]*.The OP had [a-z][a-zA-Z]* in his code, so presumably he know what that means and wants that String not to match.

Similar Messages

  • Problems with regular expressions.

    Hi all.
    I want to substitute within an xml file a string with the following structure:
    Referencer="//@Model/@OwnedElement.0/@OwnedElement.1/@OwnedElement.0/@OwnedElement.1/@OwnedElement.33 ..."
    where the dots mean that the string within the quotes may be repeated (separated by spaces) many times.
    I've tried to match such expression with java regex, with no luck. I thought running
    line.contains("Referencer=\"[^\"\\r\\n]*\"");
    would return true, but it didn't.
    Could anybody point me the right way?.
    Thank you all in advance.

    Method String.contains() does not take a regular expression - you need to use method String.matches() or class Pattern.
    This looks to be a good problem to solve using http://elliotth.blogspot.com/2004/07/java-implementation-of-rubys-gsub.html .

  • Problem with Regular Expressions

    Hi Everyone:
    I'm having a problem finding the easiest way to retrieve the replacement text that has been edited to insert back-references from previous matches. For instance,
    Lets say I want to use the below regular expression
    foo_bar([1-9])_fun
    on the search text
    foo_bar1_fun
    foo_bar2_fun
    foo_bar3_fun
    and then the replacement text would be
    foobar_fun$1
    so in the end I would get
    foobar_fun1
    foobar_fun2
    foobar_fun3
    What I would like to do is be able to extract the replacement text that has been modified with the back reference matches after I use the Matcher.appendReplacement(stringbuffer, string) method.
    So to clarify further, after I find the first match and use the appendReplacement Method, I would like to extract just the replacement that was made to the text, in this case foobar_fun1
    Thanks for any help!

    Alright, thanks for the reply. I'll try and make this a little more clear
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class LeClassName {
       public static void main(String[] args) {
          String input = "12341234foo_bar1_fun24342345foo_bar2_fun3522545foo_bar3_fun3423432";
          Pattern pattern = Pattern.compile("foo_bar([1-9])_fun");
          StringBuffer sb = new StringBuffer();
          Matcher matcher = pattern.matcher(input);
          while (matcher.find()) {
             matcher.appendReplacement(sb, "foobar_fun$1");
             //after the first pass through, I would like to extract, foobar_fun1
             // but what is in sb is 12341234foobar_fun1
          System.out.println(sb.toString());
    }I did find a solution myself after a bit of thinking but if anyone can come up with a better solution do tell and I'll award that person the answer. Thanks again!
    My Solution:
    private String fixBackReplacements() throws IndexOutOfBoundsException {
                String currentMatch = this.findMatch.group();
                Pattern temporaryPattern = Pattern.compile(findText);
                Matcher temporaryMatcher = temporaryPattern.matcher(currentMatch);
                return temporaryMatcher.replaceFirst(replaceText);
    }

  • Problem with Regular Expression: XML comment parsing

    I have create pattern to parse xml comments:
    <!--(?!.*(<!--)).*-->It works fine but only problem that I have is that it parse only last occurrence :(

    sabre150 wrote:
    MrJbee wrote:
    I have create pattern to parse xml comments:
    <!--(?!.*(<!--)).*-->It works fineI'm surprised it works fine since the ".*" is greedy and will gobble as much as it can and you will end up matching from the start of the first comment to the end of the last comment.
    but only problem that I have is that it parse only last occurrence :(Make the ".*" reluctant using ".*?" or, best of all, use an XML parser.
    Edited by: sabre150 on Jan 11, 2010 4:00 PMFirst at thanks for reply.
    Second it is not so greedy like it look. Because of that:
    (?!.*(<!--))I can`t use xml parser since It is only part of my JEditor with styles. I use reg exp to highlight comments, strings, chars and so on....
    By the way I try to replace .* => .*? and it is still no results. I mean only last is selected. Maybe you have an example on how to match structure if the do not
    have specified substrings.
    Something like this:
    hello[^(guten tag)]*bye // I know that this is wrongEdited by: MrJbee on Jan 11, 2010 1:22 PM

  • Problem with  regular expression  validation

    hi,
       how can i validate folder structure
       conditions
         no two  forward slashes(/) in a sequence no  special characters
        " /w" and   "  '/'  "    
       e:/tomcat/ss/ss.text
           if(valStr.matches("((['/'])[a-zA-Z0-9_]*)")){
                    System.out.println("matches");   
             else
                    System.out.println("notmatches");
    this is no correct .
    please give me right solution       
    with regards
    ss

    hI,
      /appmg/dd/
    is  the paths for solaris( starts with /)
    i have to test  if it is valid path name or not
    with regards
    ss

  • Urgent!!! Problem in regular expression for matching braces

    Hi,
    For the example below, can I write a regular expression to store getting key, value pairs.
    example: ((abc def) (ghi jkl) (a ((b c) (d e))) (mno pqr) (a ((abc def))))
    in the above example
    abc is key & def is value
    ghi is key & jkl is value
    a is key & ((b c) (d e)) is value
    and so on.
    can anybody pls help me in resolving this problem using regular expressions...
    Thanks in advance

    "((key1 value1) (key2 value2) (key3 ((key4 value4)
    (key5 value5))) (key6 value6) (key7 ((key8 value8)
    (key9 value9))))"
    I want to write a regular expression in java to parse
    the above string and store the result in hash table
    as below
    key1 value1
    key2 value2
    key3 ((key4 value4) (key5 value5))
    key4 value4
    key5 value5
    key6 value6
    key7 ((key8 value8) (key9 value9))
    key8 value8
    key9 value9
    please let me know, if it is not possible with
    regular expressions the effective way of solving itYes, it is possible with a recursive regular expression.
    Unfortunately Java does not provide a recursive regular expression construct.
    $_ = "((key1 value1) (key2 value2) (key3 ((key4 value4) (key5 value5))) (key6 value6) (key7 ((key8 value8) (key9 value9))))";
    my $paren;
       $paren = qr/
               [^()]+  # Not parens
             |
               (??{ $paren })  # Another balanced group (not interpolated yet)
        /x;
    my $r = qr/^(.*?)\((\w+?) (\w+?|(??{$paren}))\)\s*(.*?)$/;
    while ($_) {
         match()
    # operates on $_
    sub match {
         my @v;
         @v = m/$r/;
         if (defined $v[3]) {
              $_ = $v[2];
              while (/\(/) {
                   match();
              print "\"",$v[1],"\" \"",$v[2],"\"";
              $_ = $v[0].$v[3];
         else { $_ = ""; }
    C:\usr\schodtt\src\java\forum\n00b\regex>perl recurse.pl
    "key1" "value1"
    "key2" "value2"
    "key4" "value4"
    "key5" "value5"
    "key3" "((key4 value4) (key5 value5))"
    "key6" "value6"
    "key8" "value8"
    "key9" "value9"
    "key7" "((key8 value8) (key9 value9))"
    C:\usr\schodtt\src\java\forum\n00b\regex>

  • Problems with regular Texting since iOS 7.0.3

    Hello, I have an iPhone 5s recently upgraded to iOS 7.0.3 via OTA update. I never use iMessage, I have an unlimited text plan, so I always have used SMS with everyone. However, after this last update, I have problems with regular SMS. I can send SMS to everyone as usual, but can only get text messages from some-all of them using iPhone 5 with at least the lastest iOS6 version. I have noticed then only way to text them now is to turn on iMessage, otherwise I keep missing their replies. These are people, that until the last upgrade, I was texting with on a regular basis with no problems using plain SMS with iMessage option OFF. Contrary to most, I don't want to use iMessage but rather use regular carrier provided SMS.
    For instance, both my son and daughter use an iPhone 5 with iOS 7 (but not the latest patch 7.0.3) installed, I can text with my son OK, but can't get any texts from my daughter, can only communicate with her using iMessage-BTW, we are all on the same network on a family plan. Can't understand this at all. Since I can SMS with some, but not others I don't think this is a problem with my carrier but rather a problem with my phone since the update to 7.0.3, and they say I am the only one they have problem with texting with and I am the only one on the new software version.
    Anyone else has noticed this issue.

    I wonder if this may have something to do with iMessage on my Macs. Recently updated to Maverirks and the iMessage app on my Macs was set up to my email and mobile phone (it wasn't before). I wonder if this is so, then whoever I send an SMS to that has iMessage on and replies back, will be picked up by iMessage since is turned on on my Mac, since replies go to the Mac but not my phone. If the sender has iMessage off, I get the SMS fine.

  • Grouping & Back-references with regular expressions on Replace Text window

    I really appreciate the inclusion of the Regular Expressions in the search & replace feature. One thing I am missing is back-references in the replacement expression. For instance, in the unix tools vi or sed, I might do something like this:
    s/\(firstPart\) \(secondPart\) \(oldThirdPart\)/\2 \1 newThirdPart/g
    which would allow me to switch the places of firstPart and secondPart, and totally replace thirdPart. If grouping and back-references are already present in the Replace Text window, how does one correctly invoke them?

    duplicate of Grouping & Back-references with regular expressions on Replace Text window

  • Probleme with PCI Express Root Complex

    I bought an hp 15t - j100 with Windows 8.1 but on windows 8.1 but i needed change to windows 8 and now i have a problem with PCI Express Root Complex code 28. The drives i have donwload for hp site http://h10025.www1.hp.com/ewfrf/wc/softwareCategor​y?os=4158&lc=en&cc=us&dlc=en&sw_lang=&product=6521​...
    I need help to solve that problem
    thanks
    and i waiting for help
    This question was solved.
    View Solution.

    Hi:
    You need this driver...
    http://h10025.www1.hp.com/ewfrf/wc/softwareDownloa​dIndex?softwareitem=ob-124661-1&cc=us&dlc=en&lc=en​...

  • Assistance with Regular Expression and Tcl

    Assistance with Regular Expression and Tcl
    Hello Everyone,
      I recently began learning Tcl to develop scripts for automating network switch deployments. 
    In my script, I want to name the device with a location and the last three octets of the base mac address.
    I can get the Base MAC address by : 
    show version | include Base
     Base ethernet MAC Address       : 00:00:00:DB:CE:00
    And I can get the last three octets of the MAC address using the following regular expression. 
    ([0-9a-f]{2}[:-]){2}([0-9a-f]{2}$)
    But I have not been able to figure out how to call the regular expression in the tcl script.
    I have checked several resources but have not been able to figure it out.  Suggestions?
    Ultimately, I want to set the last three octets to a variable (something like below) and then call the variable when I name the switch.
    set mac [exec "sh version | i Base"] (include the regular expression)
    ios_config "hostname location$mac"
    Thanks for any assistance in advance.
    Chris

    This worked for me.
    Switch_1(tcl)#set result [exec show ver | inc Base]   
    Base ethernet MAC Address       : 00:1B:D4:F8:B1:80
    Switch_1(tcl)#regexp {([0-9A-F:]{8}\r)} $result -> mac
    1
    Switch_1(tcl)#puts $mac                               
    F8:B1:80
    Switch_1(tcl)#ios_config "hostname location$mac"      
    %Warning! Hostname should contain at least one alphabet or '-' or '_' character
    locationF8:B1:80(tcl)#

  • How to search with regular expression

    I make pdx files so that I can search text quickly. But Acrobat doesn't provide a way to search with regular expression. I'm wondering if there is a way that I don't know to search for regular expression in Acrobat Pro 9?

    First, Acrobat must "mount" the PDX.
    As "Find" does not use the cataloged index, use Shift+Ctrl+F to open the advanced search dialog.
    It may be helpful to first enter Acrobat Preferences and for the Search category tick "Always use advanced search options".
    Back to the Search dialog - use the drop down menu for "Look In" to pick "Select Index" then, if no PDXs show, click the Add button.
    In the Open Index File dialog, browse to the location of the desired PDX and select it.
    OK out and use "Return results containing" to pick a "Match ..." requirement or Boolean.
    To become familiar with query syntax, for Acrobat, it is good to review Acrobat Help.
    http://help.adobe.com/en_US/Acrobat/9.0/Professional/WS58a04a822e3e50102bd615109794195ff-7 c4b.w.html
    Be well...

  • Get the string between li tags, with regular expression

    I have a unordered list, and I want to store all the strings between the li tags (<li>.?</li>)in an array:
    <ul>
    <li>This is String One</li>
    <li>This is String Two</li>
    <li>This is String Three</li>
    </ul>
    This is what have so far:
    <li>(.*?)</li>
    but it is not correct, I only want the string without the li tags.
    Thanks.

    No one?
    Anoyone here experienced with Regular Expression?

  • Problem with Airport express N (2nd gen)

    Problem with Airport express N (2nd gen)
    Firmware 7.6.4
    ISP - 20 Mbps ethernet cable
    I have MacBook Air 13 mid 2013 os x 10.9.5, ipad 4 ios 8.0.2, ipad4 ios 7.1.2 , iphone 5 ios 7.1.1
    When i try to use speedtest.net from my Macbook i got good results of download speed and incredible upload http://www.speedtest.net/my-result/3801286946 (connection 300 Mbps) , both ipads got terrible speedtest download result and incredible uploadhttp://www.speedtest.net/my-result/i/981631804 (connection 150 Mbps), iphone 5 got bad download and great uploadhttp://www.speedtest.net/my-result/i/981695357.
    All these tests were done near airport express with really good signal and 5ghz. I tried to choose different channels, 802.11 mode, guest ssid, 5ghz ssid ...
    I think that something is wrong with my new airport express. Can anyone help me to solve this problem?
    ps sorry for my bad english

    As a last resort, try a factory default reset on the AirPort Express as follows:
    Power off the AirPort Express
    Wait a minute
    Hold in the reset button first, and keep holding it in for another 8-10 seconds while you simultaneously plug the Express back in to power
    Release the reset button after the hold period and allow a full minute for the Express to restart to a slow, blinking amber light status
    On an iPhone or iPad home screen....
    Tap Settings
    Tap WiFi
    Look for a heading of Setup a New AirPort Base Station. If it appears.....
    Tap on AirPort Express just below the heading to start the configuration process on the Express again
    If you try several factory default resets, and the AirPort Express does not appear under the heading of Setup a New AirPort Base Station, the Express most likely is defective and will need to be replaced.

  • CFFORM (Flash) Validation with Regular Expressions Not Working

    I am having troubles getting regular expression validation to
    work in a CFFORM. The below code is an extract of a much larger
    form, the first name and last name have a regular expression
    validation...and it doesn't work!
    I'd appreciate any comments/info for help on this, have
    searched high and low on information to get this working...but no
    joy.
    The code is:
    <cffunction name="checkFieldSet" output="false"
    returnType="string">
    <cfargument name="fields" type="string" required="true"
    hint="Fields to search">
    <cfargument name="form" type="string" required="true"
    hint="Name of the form">
    <cfargument name="ascode" type="string" required="true"
    hint="Code to fire if all is good.">
    <cfset var vcode = "">
    <cfset var f = "">
    <cfsavecontent variable="vcode">
    var ok = true;
    var msg = "";
    <cfloop index="f" list="#arguments.fields#">
    <cfoutput>
    if(!mx.validators.Validator.isValid(this,
    '#arguments.form#.#f#')) { msg = msg + #f#.errorString + '\n';
    ok=false; }
    </cfoutput>
    </cfloop>
    </cfsavecontent>
    <cfset vcode = vcode & "if(!ok)
    mx.controls.Alert.show(msg,'Validation Error'); ">
    <cfset vcode = vcode & "if(ok) #ascode#">
    <cfset vcode =
    replaceList(vcode,"#chr(10)#,#chr(13)#,#chr(9)#",",,")>
    <cfreturn vcode>
    </cffunction>
    <cfform name="new_form" format="flash" width="600"
    height="600" skin="halosilver" action="new_data.cfc">
    <cfformgroup type="panel" label="New Form"
    style="background-color:##CCCCCC;">
    <cfformgroup type="tabnavigator" id="tabs">
    <cfformgroup type="page" label="Step 1">
    <cfformgroup type="hbox">
    <cfformgroup type="panel" label="Requestor Information"
    style="headerHeight: 13;">
    <cfformgroup type="vbox">
    <cfinput type="text" name="reqName" width="300"
    label="First Name:" validate="regular_expression" pattern="[^0-9]"
    validateat="onblur" required="yes" message="You must supply your
    First Name.">
    <cfinput type="text" name="reqLname" width="300"
    label="Last Name:" validate="regular_expression" pattern="[^0-9]"
    validateat="onblur" required="yes" message="You must supply your
    Last Name.">
    <cfinput type="text" name="reqEmail" width="300"
    label="Email:" validate="email" required="yes" message="You must
    supply your email or the address given is in the wrong format.">
    <cfinput type="text" name="reqPhone" width="300"
    label="Phone Extension:" validate="integer" required="yes"
    maxlength="4" message="You must supply your phone number.">
    </cfformgroup>
    </cfformgroup>
    </cfformgroup>
    <cfformgroup type="horizontal"
    style="horizontalAlign:'right';">
    <cfinput type="button" width="100" name="cnt_step2"
    label="next" value="Next"
    onClick="#checkFieldSet("reqName,reqLname,reqEmail,reqPhone","new_form","tabs.selectedInd ex=tabs.selectedIndex+1")#"
    align="right">
    </cfformgroup>
    </cfformgroup>
    </cfformgroup>
    </cfformgroup>
    </cfform>

    quote:
    Originally posted by:
    Luckbox72
    The problem is not the Regex. I have tested 3 or 4 different
    versions that all work on the many different test sites. The
    problem is it that the validation does not seem to work. I have
    changed the patter to only allow NA and I can still type anything
    into the text box. Is there some issue with useing Regex as your
    validation?
    Bear in mind that by default validation does not occur until
    the user attempts to submit the form. If you are trying to control
    the characters that the user can enter into the textbox, as opposed
    to validating what they have entered, you will need to provide your
    own javascript validation.

  • Problem forming regular expression

    Hi,
    I want to use regular expression to match a repeating pattern until it meets a particular character. Eg.
    The string I am trying to match is a function definition.
    function abc()
    This is the pattern I am using to match the above string.
    Pattern p =
    Pattern.compile("function abc.*\r*\n*\\{(\r*\n*.*)*(\r\n)*\\}", Pattern.MULTILINE);
    "function abc" takes care of the method signature
    " .*\r*\n*\\{" takes care of all spaces/characters/newline till it encounters the opnening brace
    "(\r*\n*.*)*" this iswhere the problem lies. This matches all the individual new lines in the method body. But I dont want it to match the closing brace "}" . It is doing that currently. How can I avoid that? So that the next part of the pattern i.e. "\\}" actually matches the closing brace?

    DrLaszloJamf wrote:
    Isn't the basic difference between regular grammars and context free grammars? The latter can generate matched parens, the former can't?I guess you mean by "regular grammar" a "regular language" (forgive my ignorance if they are the same)? But yes, AFAIK that is a difference. However, there are regex engines that can cope with these recursive matches (an undefined number of back references). Perl is one of them.
    It is an often heard complaint about implementations of regular expression engines: they have grown too big for what they were created for.

Maybe you are looking for

  • Can't get it to stop CCing myself on mail

    I'm using a Google mail account with my iPhone. I went into Mail Settings and turned "Always Bcc myself" to OFF. However, it keeps sending me copies of emails I send out. What's going on? This is really bugging me, any help is greatly appreciated.

  • Textfield Title to populate in the subject line of a email button

    I need for the a textfield title to automatically populate in the subject line of the email button What code goes in sub = ?   var sub sub = var ebody Thanks

  • File Save as - Box: how to do this in jsp ??

    hi, i need a button in my jsp which opens a box, where you can choose a path and write a filename, sothat this file can be saved in this path. but i don't know why... i'm a beginner .. thanks

  • WLST script deploy EAR File in Weblogic Server

    Hi, Can any one help me providing the steps to deploy EAR file using WLST Script. Thanks in Advance. Regards Balaji S

  • EM (DB console) configuration after switchover

    Hello Guys, I have this scenario: - Oracle 11.2.0.3 - RHEL 4.6 64 bits - Active Data Guard - Broker configured - DBconsole configured on primary server Now, I have server PRIM with the primary database, and server STB with the standby server. For now