如何编写匹配两个特定字符之间的任何内容的正则表达式?
喜欢:
ignore me [take:me] ignore me
?
我怎样才能匹配包容性[take:me]
?
这个词take:me
是动态的,所以我也想匹配[123as d:.-,§""§%]
您可以使用此正则表达式:
"\\[(.*?)\\]"
此链接应该可以帮助您了解它的工作原理。
Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher matcher = pattern.matcher("ignore me [take:me] ignore me");
if (matcher.find()) {
System.out.println(matcher.group(1));
}
这将打印take:me
.
如果你想匹配&([take:me])
你应该使用这个:
&\\(\\[(.*?)\\]\\)
并不是说您应该在正则表达式中转义具有特殊含义的字符。(如(
和)
)。
转义它们是通过添加一个反斜杠来完成的,但是因为 Java 中的反斜杠是这样编写的,\\
所以你\\
在任何具有特殊含义的字符之前添加。因此,您这样做是\\(
在告诉 Java:“作为常规字符而不是特殊字符”。(
java.util.regex.Matcher类用于在文本中搜索多次出现的正则表达式。您还可以使用 Matcher 在不同文本中搜索相同的正则表达式。
Matcher 类有很多有用的方法。有关完整列表,请参阅 Matcher 类的官方 JavaDoc。我将在这里介绍核心方法。以下是涵盖的方法列表:
创建匹配器
创建 Matcher 是通过 Pattern 类中的 matcher() 方法完成的。这是一个例子:
String text =
"This is the text to be searched " +
"for occurrences of the http:// pattern.";
String patternString = ".*http://.*";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
火柴()
Matcher 类中的 matches() 方法在创建 Matcher 时将正则表达式与传递给 Pattern.matcher() 方法的整个文本进行匹配。这是一个例子:
boolean matches = matcher.matches();
如果正则表达式匹配整个文本,则 matches() 方法返回 true。如果不是,matches() 方法返回 false。
您不能使用 matches() 方法在文本中搜索多次出现的正则表达式。为此,您需要使用 find()、start() 和 end() 方法。
看着()
lookingAt() 方法的工作方式与matches() 方法类似,但有一个主要区别。lookingAt() 方法仅将正则表达式与文本的开头进行匹配,而matches() 将正则表达式与整个文本进行匹配。换句话说,如果正则表达式匹配文本的开头而不是整个文本,则lookingAt() 将返回true,而matches() 将返回false。
这是一个例子:
String text =
"This is the text to be searched " +
"for occurrences of the http:// pattern.";
String patternString = "This is the";
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
System.out.println("lookingAt = " + matcher.lookingAt());
System.out.println("matches = " + matcher.matches());
查找()+开始()+结束()
find() 方法在创建 Matcher 时搜索传递给 Pattern.matcher(text) 方法的文本中出现的正则表达式。如果可以在文本中找到多个匹配项,则 find() 方法将找到第一个匹配项,然后对于随后对 find() 的每次调用,它将移动到下一个匹配项。
方法 start() 和 end() 将为找到的匹配开始和结束的文本提供索引。
这是一个例子:
String text =
"This is the text which is to be searched " +
"for occurrences of the word 'is'.";
String patternString = "is";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
int count = 0;
while(matcher.find()) {
count++;
System.out.println("found: " + count + " : "
+ matcher.start() + " - " + matcher.end());
}
此示例将在搜索的字符串中四次找到模式“is”。打印的输出将是这样的:
发现:1 : 2 - 4
发现:2 : 5 - 7
发现:3 : 23 - 25
发现:4 : 70 - 72
你也可以参考这些教程..
试试你正在使用的字符在(?<=c)(.+)(?=c)
哪里c