tags:

views:

65

answers:

3

i dont undestand the () in regexp.

eg. what is the difference between these lines:

"/hello/"
"/(hello)/"
+1  A: 

By wrapping it in ( and ) you can capture it and handle it as a whole. Suppose we have the following text:

hellohello hello!

If I wanted to find the word "hello" in two's, I could do this:

/hellohello/

Or, I could do this:

/(hello){2}/
Jonathan Sampson
so the above example would give the same result?
weng
For finding "hello" twice, yes. You could manually put it in twice if you wanted, but imagine something like `/(hello){50}/`. This is a very limited demonstration though.
Jonathan Sampson
nice example..gave u green one for that:) could u please explain these two () in the following code, i cant understand it: '/<a([^>]+)\>(.*?)\<\/a\>/i'
weng
It's a backreference. Typically these are used to store parts of the expression for later use. You can see the following question for an example of backreferences: http://stackoverflow.com/questions/1695427/php-regular-expression-replace
Jonathan Sampson
+6  A: 

() provide a way to capture matches and for grouping take a look here for a more full description.

rerun
A: 

As you have written it, there is no actual difference between the two examples. But parantheses allow you to apply post-logic to that entire group of characters (e.g. as another poster used as an example, {2} afterwards would state the the string "hello" is typed two times in a row without anything in between - hellohello. Parantheses also allow you to use "or" statements - "/(hello|goodbye)/" would match EITHER hello OR goodbye.

The most powerful use of them however is extracting data from a string, rather than just matching it, it lets you pull the data out of the string and do what you want with it.

e.g. in PHP if you did

preg_replace( "/hello (.+)/i", "hello how are you?", $holder );`

Then $holder[1] will contain ALL the text after "hello ", which in this case would be "how are you?"

Sean