在Python中,`$`符号在正则表达式中有特殊的含义。以下是`$`符号在Python正则表达式中的用法:
匹配字符串末尾
默认情况下,`$`匹配输入字符串的末尾。
```python
import re
s = "123 abc"
print(re.findall(r'^[0-9]$', s)) 输出:1
print(re.findall(r'[0-9]$', s)) 输出:空列表,因为字符串不以数字结尾
多行模式下的匹配
当使用`re.MULTILINE`标志时,`$`会匹配每一行的末尾,包括换行符。
```python
import re
s = "123\nabc\n456"
print(re.findall(r'^[0-9]$', s, re.MULTILINE)) 输出:['123', '456']
匹配字符串中的`$`字符本身
若要匹配`$`字符本身,需要使用`\\$`进行转义。
```python
import re
s = "The price is $100."
print(re.findall(r'\\$', s)) 输出:['$']
请注意,在Python中,`$`作为变量名的一部分是不合法的,会导致语法错误。如果你需要在正则表达式中使用`$`,请确保正确转义或使用`\\$`