String Literals
此 API 支持的 Pattern 匹配的最基本形式是字符串Literals 的匹配。例如,如果正则表达式为foo
且 Importing 字符串 为foo
,则匹配将成功,因为字符串 相同。使用测试工具进行try:
Enter your regex: foo
Enter input string to search: foo
I found the text foo starting at index 0 and ending at index 3.
这场 match 很成功。请注意,尽管 Importing 字符串 的 Long 度为 3 个字符,但开始索引为 0,结束索引为 3.按照惯例,范围包括开始索引和结束索引,如下图所示:
字符串Literalsfoo,带有编号的单元格和索引值。
字符串 中的每个字符都位于其自己的单元格中,索引位置指向每个单元格之间。即使字符本身仅占用单元格 0、1 和 2,字符串“ foo”也从索引 0 开始,到索引 3 结束。
在随后的 match 中,您会发现一些重叠;下一场 match 的开始索引与上一场 match 的结束索引相同:
Enter your regex: foo
Enter input string to search: foofoofoo
I found the text foo starting at index 0 and ending at index 3.
I found the text foo starting at index 3 and ending at index 6.
I found the text foo starting at index 6 and ending at index 9.
Metacharacters
该 API 还支持许多特殊字符,这些特殊字符会影响 Pattern 的匹配方式。将正则表达式更改为cat.
,将 Importing 字符串 更改为cats
。输出将如下所示:
Enter your regex: cat.
Enter input string to search: cats
I found the text cats starting at index 0 and ending at index 4.
即使 Importing 字符串 中不存在点“ .
”,匹配仍然成功。它之所以成功,是因为该点是一个元字符,即由匹配器解释的具有特殊含义的字符。元字符“。”表示“任何字符”,这就是在此示例中匹配成功的原因。
此 API 支持的元字符为:<([{\^-=$!|]})?*+.>
Note:
在某些情况下,上面列出的特殊字符将不被视为元字符。当您了解有关如何构造正则表达式的更多信息时,将遇到此问题。但是,您可以使用此列表来检查特定字符是否曾经被视为元字符。例如,字符@
和#
从不带有特殊含义。
有两种方法可以强制将元字符视为普通字符:
-
在元字符之前加反斜杠,或者
-
将其括在
\Q
(以引号开始)和\E
(以引号结束)之内。
使用此技术时,只要\Q
在前,则\Q
和\E
可以放在表达式中的任何位置。