描述
此正则表达式会将请求的字符串部分返回到请求的组中。是可选的and
,如果在字符串中找不到它,则整个字符串被放入组 1。所有\s*?
捕获的组都强制自动修剪其空白。
^\s*?\b(.*?)\b\s*?(?:\b(and)\b\s*?\b(.*?)\b\s*?)?$
团体
0 获取整个匹配字符串
- 获取分隔词之前的字符串
and
,如果没有and
则整个字符串出现在这里
- 得到分隔词,在这种情况下是
and
- 获取字符串的第二部分
Java 代码示例:
情况1
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Module1{
public static void main(String[] asd){
String sourcestring = "foo sentence A AND foo sentence B";
Pattern re = Pattern.compile("^\\s*?\\b(.*?)\\b\\s*?(?:\\b(and)\\b\\s*?\\b(.*?)\\b\\s*?)?$",Pattern.CASE_INSENSITIVE);
Matcher m = re.matcher(sourcestring);
if(m.find()){
for( int groupIdx = 0; groupIdx < m.groupCount()+1; groupIdx++ ){
System.out.println( "[" + groupIdx + "] = " + m.group(groupIdx));
}
}
}
}
$matches Array:
(
[0] => foo sentence A AND foo sentence B
[1] => foo sentence A
[2] => AND
[3] => foo sentence B
)
案例2,使用相同的正则表达式
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Module1{
public static void main(String[] asd){
String sourcestring = "foo sentence A";
Pattern re = Pattern.compile("^\\s*?\\b(.*?)\\b\\s*?(?:\\b(and)\\b\\s*?\\b(.*?)\\b\\s*?)?$",Pattern.CASE_INSENSITIVE);
Matcher m = re.matcher(sourcestring);
if(m.find()){
for( int groupIdx = 0; groupIdx < m.groupCount()+1; groupIdx++ ){
System.out.println( "[" + groupIdx + "] = " + m.group(groupIdx));
}
}
}
}
$matches Array:
(
[0] => foo sentence A
[1] => foo sentence A
)