我有一個帶有字符串的大數組。現在,我需要使用數組中的字符串來形成模式。但是對於帶有圓括號的字符串,構造的模式不起作用。任何人都可以指出什麼是錯的?謝謝。檢測圓括號的正則表達式
這裏是我的代碼:
String[] phrases = new String[2];
phrases[0] = "student (male)";
phrases[1] = "worker (female)";
Pattern[] ptn = new Pattern[phrases.length];
int i = 0;
for (String p : phrases)
{
p = p.replaceAll("\\(", "\\\\(");
p = p.replaceAll("\\)", "\\\\)");
System.out.println(p);
ptn[i] = Pattern.compile(p+"\\:\\s\\w+");
i++;
}
String text = "Student (male): John";
for(Pattern p : ptn)
{
Matcher m = p.matcher(text);
while(m.find())
{
System.out.println(m.group());
}
}
}
它的工作原理!謝謝! – user3321400