2 回答
TA贡献1804条经验 获得超7个赞
这个表达式可能只是工作:
^[LMR]*$
测试
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final String regex = "^[LMR]*$";
final String string = "MMMRMMMRMMLLMMK\n"
+ "MMMRMMMRMMLLMM\n"
+ "L\n"
+ "M\n"
+ "R\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
TA贡献1850条经验 获得超11个赞
我更愿意在这里使用String#matches简单的模式[LMR]*:
String input = "MMMRMMMRMMLLMM";
if (input.matches("[LMR]*")) {
System.out.println("MATCH");
}
else {
System.out.println("NO MATCH");
}
请注意,String#match默认情况下假定围绕模式开始和结束锚点,因此我们甚至不需要提供^and $。
添加回答
举报