[英]Question about Java regex
我從數組列表中獲取一個字符串:
array.get(0).toString()
給TITLE =“blabla”
我想要字符串blabla,所以我試試這個:
Pattern p = Pattern.compile("(\".*\")");
Matcher m = p.matcher(array.get(0).toString());
System.out.println("Title : " + m.group(0));
它不起作用: java.lang.IllegalStateException: No match found
我也嘗試:
Pattern p = Pattern.compile("\".*\"");
Pattern p = Pattern.compile("\".*\"");
Pattern p = Pattern.compile("\\\".*\\\"");
在我的程序中沒有任何匹配,但所有模式都在http://www.fileformat.info/tool/regex.htm上工作
任何想法? 提前致謝。
幾點:
Javadoc for Matcher#group聲明:
IllegalStateException - 如果尚未嘗試匹配,或者上一個匹配操作失敗
也就是說,在使用組之前,必須首先使用m.matches
(以匹配整個序列),或m.find
(以匹配子序列)。
其次,你實際上想要m.group(1)
,因為m.group(0)
是整個模式。
實際上,這不是很重要,因為有問題的正則表達式以捕獲括號開始和結束,因此group(0)與group(1)是相同的字符串,但是如果你的正則表達式看起來像是這樣的話: "TITLE = (\\".*\\")"
示例代碼:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
@SuppressWarnings("serial")
public class MatcherTest {
@Test(expected = IllegalStateException.class)
public void testIllegalState() {
List<String> array = new ArrayList<String>() {{ add("Title: \"blah\""); }};
Pattern p = Pattern.compile("(\".*\")");
Matcher m = p.matcher(array.get(0).toString());
System.out.println("Title : " + m.group(0));
}
@Test
public void testLegal() {
List<String> array = new ArrayList<String>() {{ add("Title: \"blah\""); }};
Pattern p = Pattern.compile("(\".*\")");
Matcher m = p.matcher(array.get(0).toString());
if (m.find()) {
System.out.println("Title : " + m.group(1));
}
}
}
您需要首先在Matcher實例上調用find()
或matches()
:這些實際執行正則表達式並返回它是否匹配。 然后,只有匹配時,您才能調用方法來獲取匹配組。
你在字符串中包含雙引號(“)嗎?
你的所有正則表達式都已經轉義了,只有當列表中的字符串包含雙引號字符時才會匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.