[英]Find some text in a string on matching to a reg-ex
我正在尋找形式的句子。 文本文檔的每一行的第三字段中的“ .... X在Y ...上受教育”。 X是已知的,Y是未知的。 成功匹配后,如何獲得Y的值? 以下是我的代碼:
Pattern p1 = Pattern.compile(".* educated at .*");
int count = 0;
while((line = br.readLine()) != null){
String datavalue[] = line.split("\t");
String text = datavalue[2];
Matcher m = p1.matcher(text);
if(m.matches()){
count++;
//System.out.println(text);
//How do I get Y?
}
}
我是reg-ex的新手。 任何幫助表示贊賞。
將找到的文本捕獲為一組:
Pattern p1 = Pattern.compile(".* educated at (.*)");//note the parenthesis
int count = 0;
while((line = br.readLine()) != null){
String datavalue[] = line.split("\t");
String text = datavalue[2];
Matcher m = p1.matcher(text);
if(m.matches()){
count++;
System.out.println(m.group(1));
}
}
請參閱https://docs.oracle.com/javase/tutorial/essential/regex/groups.html了解更多信息
您可以一行完成:
while((line = br.readLine()) != null){
String y = line.replaceAll(".*?\t.*?\t{^\t]*educated at (\\w+).*|.*", "$1");
如果沒有匹配項,則變量y
將為空白。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.