2014-04-29 64 views
1

這裏是我的代碼以符合像一個字符串:使用正則表達式從輸入解析字符串

String name = qualified.replaceAll(".*\\.(?=\\w+)", ""); 

凡從輸入org.myapp.TestData$RootEntity得到一個TestData$RootEntity

不過,我需要能夠得到公正的RootEntity部分字符串。有效地獲得這一點。

輸入字符串:

com.domain.app.RootEntity 

com.domain.app.TestData$RootEntity 

com.domain.app.TestData$TestNested$RootEntity 

,應該能夠得到RootEntity

+0

使用'string.lastIndexOf( '$')' – Braj

回答

1

試試這個:

String name = qualified.replaceAll(".+?\\W", ""); 

.*\\W匹配之前的一切$.,並用空字符串替換它。

+0

對於輸入字符串「com.domain.app.RootEntity」它返回空,即噸應該返回RootEntity – xybrek

+0

@xybrek,現在它的工作 –

+0

@xybrek,很高興有幫助。 –

1

簡單String#lastIndexOf()

String qualified = "org.myapp.TestData$RootEntity"; 

    String name = qualified.substring(qualified.lastIndexOf('$') + 1); 

完整代碼嘗試

String[] values = new String[] { "com.domain.app.RootEntity", 
      "com.domain.app.TestData$RootEntity", 
      "com.domain.app.TestData$TestNested$RootEntity" }; 

    for (String qualified : values) { 
     int index = qualified.lastIndexOf('$'); 

     String name = null; 
     if (index != -1) { 
      name = qualified.substring(qualified.lastIndexOf('$') + 1); 
     } else { 
      name = qualified.substring(qualified.lastIndexOf('.') + 1); 
     } 

     System.out.println(name); 
    } 

輸出:

RootEntity 
RootEntity 
RootEntity 
0

簡單:

String resultString = qualified.replaceAll("(?m).*?(RootEntity)$", "$1"); 
0
com.domain.app.RootEntity 
com.domain.app.TestData$RootEntity 
com.domain.app.TestData$TestNested$RootEntity 

,應該能夠得到RootEntity

在貌似要刪除它有後.$app.TestData$名的每個部分。

如果是這樣的話,你可以嘗試

replaceAll("\\w+[.$]", "") 

演示

String[] data = { 
     "com.domain.app.RootEntity", 
     "com.domain.app.TestData$RootEntity", 
     "com.domain.app.TestData$TestNested$RootEntity", 
}; 
for (String s:data) 
    System.out.println(s.replaceAll("\\w+[.$]", "")); 

輸出:

RootEntity 
RootEntity 
RootEntity 
相關問題