Regular expression brackets target

I don't know how () in regex.

eg. what is the difference between these lines:

"/hello/" "/(hello)/" 
+4
source share
3 answers

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

hellohello hello!

If I wanted to find the word β€œhello” in two, I could do this:

 /hellohello/ 

Or I could do this:

 /(hello){2}/ 
+1
source

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

+6
source

As you wrote it, there is no actual difference between the two examples. But the brackets allow you to apply post-logic to the entire group of characters (for example, as another poster used as an example, {2} will subsequently indicate that the string "hello" is typed twice in a row without anything in between - hellohello Parantheses also allows you to use "or" statements - "/ (hello | goodbye) /" will match EITHER hi or goodbye.

The most powerful of them is extracting data from a row, and not just combining them, it allows you to pull data from a row and do what you want with it.

eg. 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 will be "how are you?"

+1
source

Source: https://habr.com/ru/post/1301887/


All Articles