What's the point of using parenthesis in regex if you're not remembering the matched part?
Why would you use \(?:\d+)alp*ha\
rather than \\d+alp*ha\
开发者_如何学编程??
In your example, there is no reason to add the parenthesis. However consider the following:
/(?:\d+A?)*alp*ha/
In that example, the parenthesis define a group that can be repeated. This would be impossible to express without parenthesis. (Without parenthesis - /\d+A?*alp*ha/
- is something completely different.)
In the example, there is no point to using the non-capturing parentheses; they may be a leftover relic from a previous more complex expression.
In general, if you have a more complex expression, perhaps with alternatives or you need to qualify a string, then the non-capturing parentheses are useful.
(?:\d+|abc)?alp*ha
This requires the non-capturing parentheses.
You probably have a problem with escaped (or unescaped) backslashes in the example.
Regular expression syntax is like algebraic syntax in that there are operators with precedence. The parenthesis (all sorts of them) do double-duty: explicit control of operator binding and various sorts of grouping, stashing, and searching tweaks.
精彩评论