[英]examples on how to parse string in java
我有以下字符串需要解析/提取其中的“ 20000”。
"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);
困惑之后該怎么辦?
您可以使用此正則表達式從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 =
}
}
嘗試這個:
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());
}
浮點數和負數
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.