[英]extract substring in java using regex
我需要從字符串中提取"URPlus1_S2_3"
:
"Last one: http://abc.imp/Basic2#URPlus1_S2_3,"
使用Java語言中的正則表達式。
有人可以幫幫我嗎? 我是第一次使用正則表達式。
嘗試
Pattern p = Pattern.compile("#([^,]*)");
Matcher m = p.matcher(myString);
if (m.find()) {
doSomethingWith(m.group(1)); // The matched substring
}
String s = "Last one: http://abc.imp/Basic2#URPlus1_S2_3,";
Matcher m = Pattern.compile("(URPlus1_S2_3)").matcher(s);
if (m.find()) System.out.println(m.group(1));
您將學習如何指定要求;)
您尚未真正定義查找該字符串所需使用的條件,但是這是一種基於“#”分隔符的方法。 您可以根據需要調整正則表達式。
expr: .*#([^,]*)
extract: \1
轉到此處獲取語法文檔:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
String s = Last one: http://abc.imp/Basic2#URPlus1_S2_3,"
String result = s.replaceAll(".*#", "");
如果沒有“#”,則上面的代碼將返回完整的String。 使用正則表達式有更好的方法,但是最好的解決方案是不使用正則表達式。 有類URL和URI來完成這項工作。
因為這是您第一次使用正則表達式,所以我建議您采用另一種方式,這種方式現在更容易理解(直到您掌握正則表達式;為止),並且如果需要,可以很容易地對其進行修改:
String yourPart = new String().split("#")[1];
這是一個 長版本:
String url = "http://abc.imp/Basic2#URPlus1_S2_3,";
String anchor = null;
String ps = "#(.+),";
Pattern p = Pattern.compile(ps);
Matcher m = p.matcher(url);
if (m.matches()) {
anchor = m.group(1);
}
要理解的要點是括號的使用,它們用於創建可以從模式中提取的組。 在Matcher
對象中, group
方法將從索引1開始按順序返回它們,而完全匹配由索引0返回。
如果只需要#
之后的所有內容,請使用split:
String s = "Last one: http://abc.imp/Basic2#URPlus1_S2_3," ;
System.out.println(s.split("#")[1]);
或者 ,如果您想解析URI並獲取片段組件,則可以執行以下操作:
URI u = new URI("http://abc.imp/Basic2#URPlus1_S2_3,");
System.out.println(u.getFragment());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.