正则表达式:查找字符串中的模式

时间:2019-04-28 20:22:09

标签: java regex string

有人可以解释如何在Java中使用正则表达式。我有几个字符串Dim objExcel, objWorkbook, objWorksheet1 Dim iDelCnt, jDelCnt, projectFilter, lRow, fixVerColNum, tempCell, deleteCounter, InStrTest Set objExcel = CreateObject("Excel.Application") objExcel.Application.Visible = True Set objWorkbook = objExcel.Workbooks.Open(filePath) ' Location of the file on drive Set objWorksheet1 = objWorkbook.Worksheets(1) projectFilter = Array("Project 1","Project 2", "Project 3") fixVerColNum = objExcel.Match("Fix Version/s", objWorksheet1.Range("A1:T1"), 0) 'Identify "Fix Version(s)" column number lRow = objWorksheet1.Range("A1").CurrentRegion.Rows.Count deleteCounter = 0 For iDelCnt = lRow to 2 Step -1 For jDelCnt = LBound(projectFilter) to UBound(projectFilter) If InStr(1, objWorksheet1.Cells(iDelCnt, fixVerColNum).Value, projectFilter(jDelCnt), 1) <> 0 Then deleteCounter = 1 Exit For Else deleteCounter = 0 End If Next If deleteCounter = 0 Then objWorksheet1.Rows(iDelCnt).EntireRow.Delete End If Next 3 :- N, ‘V—g'ufi “ ‘L Total: 13-70 "0- 1‘ i。我需要提取Total:及其后的总和:期望输出r _._A_ ,,1 Total: $13.70 i- T«的Ex。 我尝试使用以下代码...但是据我了解,它不会捕获符号,例如Total: 13-70, Total: $13.70

$.-

1 个答案:

答案 0 :(得分:4)

您可以使用

Total:\s*\$?\d+(?:[-.]\d+)?

请参见regex demo

详细信息

  • Total:-文字子字符串
  • \s*-超过0个空格
  • \$?-可选的$字符
  • \d+-1个以上数字
  • (?:[-.]\d+)?-一个可选的非捕获组,匹配以下情况的1或0:
    • [-.]--.
    • \d+-1个或多个数字。

enter image description here

在Java中:

Pattern p = Pattern.compile("Total:\\s*\\$?\\d+(?:[-.]\\d+)?");

如果您需要提取值,请在需要提取的模式周围使用捕获组(例如,此处为\$?\d+(?:[-.]\d+)?),然后访问该组值,例如

Pattern p = Pattern.compile("Total:\\s*(\\$?\\d+(?:[-.]\\d+)?)");
Matcher m = p.matcher(result);
while (m.find()) {
     System.out.println(m.group(1));
}