HighDots Forums  

Re: How to search a particular substring in square bracket

Javascript JavaScript language (comp.lang.javascript)


Discuss Re: How to search a particular substring in square bracket in the Javascript forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Noah Sussman
 
Posts: n/a

Default Re: How to search a particular substring in square bracket - 12-06-2006 , 07:54 AM






balakrishnan.dinesh (AT) gmail (DOT) com wrote:
Quote:
Im having a problem in searching out a particular substring in a
string.
var tmpString="[Wed May 3 18:25:14 2006] [192.168.1.61] [GET
/manual/en/images/down.gif] [304] [0] [] [396 msecs]";
var ip="[192.168.1.61]";
var arr=tmpString.match(ip)
(or)
var arr=tmpString.search(ip)

So in my tmpString variable, i have the data like this with square
brackets, Now i want to compare the ip variable value with tmpString
contained ip value, due to this sqaure brackets im not able to compare
it accurately.
Both match and search take regular expressions as their arguments.
And, if given a non-regex argument, match() and search() automatically
_convert_ that argument to a regex.

Square brackets [] are a regular expression operator. In a regex,
"[192.168.1.61]" matches _one_character,_ as long as that character is
_any_ of 1,9,2,6 or 8.

Quote:
While using "search" , it is showing error if square bracket
used.
Hmm, when I run your example code using search(), arr evaluates to 11.
11 is the position in tmpString of the first match for the regex
"[192.168.1.61]"; which is the digit "1" in "18:25:14".

Quote:
using match it is returning some interger.
Agreed. Using match() in your example, arr evaluates to 1. In this
case, match() is returning the string that was matched. But the regex
"[192.168.1.61]" only matches one character, the 1 in "18:25:14".

If you escape each of the square brackets in ip with a double
backslash, you should get more reasonable results:

var ip="\\[192.168.1.61\\]";
var tmpString="[Wed May 3 18:25:14 2006] [192.168.1.61]
[GET/manual/en/images/down.gif] [304] [0] [] [396 msecs]";
var matched=tmpString.match(ip);
var searched=tmpString.search(ip);

Now matched should contain "[192.168.1.61]", which is the part of
tmpString that matches ip. And searched should contain "26", which is
the position in tmpString of the first character of the substring that
matches ip.



Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.