我对Regex不太熟悉,一直在尝试将以下问题简化为一个表达式。第一个示例将始终具有{Container:}
,第二个示例将始终具有{Container: randomname Running · random# GPM · randomitem}
,其中Running
也可能是Offline
和Stopped
。
问题1:
我想缩小表达范围:
{Container: Jake}
所需的正则表达式替换结果:“Jake”
当前解决方案:
String test = {Container: Jake}
Regex.Replace(test.ToString(), "{Container:", "");
Regex.Replace(test,"}", "");
问题2
我想缩小表达范围:
{Container: Jake Running · 56 GPM · Beans}
所需的正则表达式替换结果:“Running”
String test = {Container: Jake Running · 56 GPM · Beans }
Regex.Replace(test.ToString(), "{Container:", ""); //Gets rid of specific expression
Regex.Replace(test,"}", ""); //Gets rid of only } curly bracket
Regex.Replace(app_values.all_devices_status, @"\b(?!Running|Stopped)\b\w*",""); //gets ride of everything except “Running · ·” Problem is this expression leaves in dots
Regex.Replace(app_values.all_devices_status, "[^a-zA-Z]+", ""); //gets only the alphabet letters
答案 0 :(得分:1)
两种情况下,您都有两种选择:使用环视功能在完全匹配中获得所需的结果,或使用捕获组提取结果。
使用环视功能捕获{Container:
... }
(?<={Container:\s).*?(?=})
(?<={Container:\s\w+\s)\w+(?=\s.*?})
第二种模式仅在.NET正则表达式引擎中有效,该引擎允许在环视中使用量词。
使用捕获组提取结果
{Container:\s(\S+)}
{Container:\s\w+\s(\S+)\s.*?}
答案 1 :(得分:0)
此表达式
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(report);
// report is a HashMap List of Data collected from database
InputStream inputStream = this.getClass().getResourceAsStream("xyz.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(inputStream);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource);
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JRXlsxExporter jrXlsxExporter = new JRXlsxExporter();
jrXlsxExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
jrXlsxExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
jrXlsxExporter.exportReport();
String fileName ="MyReport";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
response.setContentType("application/xlsx");
ServletOutputStream os = response.getOutputStream();
outputStream.writeTo(os);
os.flush();
捕获{Container:\s*([^\s}]+).*
(demo 1)和
Jake
可能会返回{Container:.*?\s*([^\s]+)\s*·.*
。
Running