如何编写匹配两个特定字符之间的任何内容的正则表达式?
像这样:
ignore me [take:me] ignore me
如何匹配包含式[take:me]
单词take:me是动态的,所以我也想匹配[123as d:.-,§""§%]
发布于 2013-04-29 15:21:31
您可以使用此正则表达式:
"\\[(.*?)\\]"
这个link应该能帮助你理解它的工作原理。
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]),你应该使用这个:
&\\(\\[(.*?)\\]\\)
这并不是说您应该在regex中转义具有特殊含义的字符。(如(和))。
转义它们是通过添加反斜杠来完成的,但是因为在Java语言中反斜杠是写成\\的,所以您可以在任何具有特殊含义的字符之前添加\\。因此,通过执行\\(,您可以告诉Java:“将(作为常规字符,而不是特殊字符”。
发布于 2013-04-29 15:28:01
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);matches()
Matcher类中的matches()方法在创建Matcher时将正则表达式与传递给Pattern.matcher()方法的整个文本进行匹配。下面是一个示例:
boolean matches = matcher.matches();如果正则表达式匹配整个文本,则matches()方法返回true。如果不是,matches()方法将返回false。
不能使用matches()方法在文本中搜索一个正则表达式的多次匹配项。为此,需要使用find()、start()和end()方法。
lookingAt()
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()+ start() +()
在创建匹配器时,find()方法在传递给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
您也可以参考这些教程。
Tutorial 1
发布于 2013-04-29 15:28:21
尝试(?<=c)(.+)(?=c),其中c是您正在使用的字符
https://stackoverflow.com/questions/16273143
复制相似问题