2015-11-03 74 views
2

我有下面的字符串,我需要解析/提取'20000'。關於如何解析java中的字符串的示例

"where f_id = '20000' and (flag is true or flag is null)" 

任何建議最好的方法來做到這一點?

這裏有更多的代碼來幫助理解:

List<ReportDto> reportDtoList = new ArrayList<ReportDto>(); 
for (Report report : reportList) { 
List<ReportDetailsDto> ReportDetailsDtoList = new ArrayList<ReportDetailsDto>(); 

ReportDto reportDto = new ReportDto(); 
reportDto.setReportId(report.getReportId()); 
reportDto.setReportName(report.getName()); 

Pattern p = Pattern.compile("=\\s'[0-9]+'"); 
String whereClause = report.getWhereClause(); 
Matcher m = p.matcher(whereClause); 

困惑在這之後該怎麼辦?

+2

你的問題是不完整的。請在其中添加更多細節。 – Pavan

+1

拆分會做這個工作 –

+0

我基本上需要得到該數值並將其設置爲我的dto – Buccaneer

回答

4

您可以使用此正則表達式來從你的String

Pattern p = Pattern.compile("[0-9]+"); 
Matcher m = p.matcher(text); 

if (m.find()) { 
    System.out.println(m.group()); 
} 

提取單個非負整數,或者,如果你想保留單引號:

Pattern p = Pattern.compile("['0-9]+"); 

這將提取包括'='模式之後有一個空間。它將打印一個String,其中包含沒有'='或空格的數字。所以,如果這符合你知道有根據您加入這個代碼'='

Pattern p = Pattern.compile("=\\s'[0-9]+"); 
Matcher m = p.matcher(text); 

if (m.find()) { 
    System.out.println(m.group().substring(3)); 
} 

編輯 後一個數字它會是什麼樣子

List<ReportDto> reportDtoList = new ArrayList<ReportDto>(); 
Pattern p = Pattern.compile("=\\s'[0-9]+"); 
for (Report report : reportList) { 
    List<ReportDetailsDto> ReportDetailsDtoList = new ArrayList<ReportDetailsDto>(); 

    ReportDto reportDto = new ReportDto(); 
    reportDto.setReportId(report.getReportId()); 
    reportDto.setReportName(report.getName()); 

    String whereClause = report.getWhereClause(); 
    Matcher m = p.matcher(whereClause); 
    if (m.find()) { 
     String foundThis = m.group().substring(3); 
     // do something with foundThis 
    } else { 
     // didn't find a number or = 
    } 
} 
+0

我應該將它包裝在if語句中,然後檢查字符串包含「=」,然後我可以解析出字符串內的數字嗎? 。 如果(a.getWhereClause()包含( 「=」){ aDto.setFId(a.getWhereClause()..... } 這是我有點困惑 – Buccaneer

+0

謝謝馬諾斯 - 是有什麼我可以添加在這裏排除在我的字符串返回的單引號 當我用你的例子中,lastMatch對我來說是: 「20000 」 10000 等... – Buccaneer

+0

對不起,我仍然有點困惑,我怎樣才能擺脫單引號? – Buccaneer

0

試試這個:

Pattern p = Pattern.compile("-?\\d+"); 
String s = "your string here"; 
Matcher m = p.matcher(s); 
List<String> extracted = new ArrayList<String>(); 
while (m.find()) { 
    extracted.add(m.group()); 
} 
0

浮動和底片

Pattern p = Pattern.compile("(-?\\d+)(\\.\\d+)?"); 
     String s = "where f_id = '20000' 3.2 and (flag is true or flag is null)"; 
     Matcher m = p.matcher(s); 
     List<String> extracted = new ArrayList<String>(); 
     while (m.find()) { 
      extracted.add(m.group()); 
     } 

     for (String g : extracted) 

      System.out.println(g); 

打印出

20000 
3.2 
+0

另一個問題 - 一旦我得到字符串值,我將如何設置它作爲一個變量,然後能夠將字符串值轉換爲整數,以便我可以將它設置到我的DTO? – Buccaneer

+0

您可以使用Integer.parseInt(「2000」) – AbtPst

+0

以便根據我的代碼,提取的List已經包含了所有數字。只是一個一個地解析它們 – AbtPst