0

假设您有这样的模式:

@[a-z]+\s[\d] 

有这样的东西有用吗:

(@[a-z]+\s[\d])

在任何情况下?它们之间有什么区别吗?怎么会这样?

4

2 回答 2

1

()用于捕获数据。如果您尝试匹配"My name is John"而不捕获:

/My name is [A-Z][a-z]+/

那么结果将只是字符串:

("My name is John")

如果您想从结果中单独捕获名称,那么您可以使用()这样的:

/My name is ([A-Z][a-z]+)/

这将返回整个匹配项(始终将整个匹配项作为第一个结果项返回是惯例),它还将返回捕获的名称,如下所示:

("My name is John", "John")

如果我们想捕获名字和姓氏,"My name is John Doe"那么我们可以这样做:

/My name is ([A-Z][a-z]+) ([A-Z][a-z]+)/

结果:

("My name is John Doe", "John", "Doe")

So, to answer your question, there is really no difference between the two expressions. The first will just match a string, while the second will match and capture it (in this case you would basicaly just end up with two identical results).

于 2013-01-25T01:47:12.573 回答
-3

通常你把它放在双引号中......

于 2013-01-24T20:36:28.467 回答