使用正则表达式,查找以"ba”结尾的字符串
时间: 2024-12-14 08:28:25 浏览: 2
在正则表达式中,如果你想查找以 "ba" 结尾的字符串,你可以直接将这两个字符放在正则表达式的末尾,通常会配合 `$` 字符,它代表字符串的结束位置。以下是几种常见编程语言的示例:
**Python**:
```python
import re
strings = ["banana", "applebacon", "cat"]
pattern = r".*ba$"
matches = [s for s in strings if re.match(pattern, s)]
print(matches) # 输出: ['banana', 'applebacon']
```
**JavaScript**:
```javascript
const regex = /.*ba$/;
const strings = ["banana", "applebacon", "cat"];
const matches = strings.filter(s => regex.test(s));
console.log(matches); // 输出: ["banana", "applebacon"]
```
**Java**:
```java
import java.util.regex.Pattern;
import java.util.regex.Matcher;
List<String> strings = Arrays.asList("banana", "applebacon", "cat");
Pattern pattern = Pattern.compile(".*ba$");
Matcher matcher = pattern.matcher("");
for (String str : strings) {
matcher.reset(str);
if (matcher.matches()) {
System.out.println(str); // 输出: ["banana", "applebacon"]
}
}
```
在以上代码中,`.` 匹配除换行符以外的任何字符,`*` 表示前面的元素可以出现0次或多次。
阅读全文