Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

RegExp matching subexpression w/o returning in result

Status
Not open for further replies.

foobar44

Programmer
Dec 15, 2007
1
0
0
HI,
Is there a way to have a subexpression in a regexp that will be matched (if it exists) but will not be returned in the result string?

EXAMPLE:

input="FAX: 555.555.5555"
re=/(?:FAX.*)\d{3}.\d{3}.d{4}/

so the resulting string would not contain the "FAX: " part?
 
Positive/negative look behind is not implemented for js engine of ie/moz common browser: not as a matter of principle, I think not. You can easily obtain the same functionality without appealling to look-behind or -ahead for that matter.
[tt]
input="FAX: 555.555.5555";
re=/(FAX:\s*)(\d{3}\.\d{3}\.\d{4})/;
var s="";
if (re.test(input)) {
s=input.replace(re,"$2");
}
//alert (s);
[/tt]
 
Another way to do this is to use the regular expressions exec function to get an object containing an array of matches. This requires the regular expression engine to do a little less work than using replace.

Code:
    function test()
    {
       var input = "FAX: 111.222.3333";
       var re = /FAX:.*(\d{3}.\d{3}.\d{4})/;
       var match = re.exec(input);
       var s;
       if (match != null)
          s = match [1];
       else
          s = "No match";
       alert(s);
    }

You can even get multiple sub parts of a string using this method like this:

Code:
    function test()
    {
       var input = "FAX: 111.222.3333";
       var re = /FAX:.*((\d{3}).(\d{3}).(\d{4}))/;
       var match = re.exec(input);
       if (match != null)
       {
          for (i=0; i<match.length; i++)
            alert(i.toString() + ": " + match[i]);
       }
       else
          alert("No match");
    }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top