java - 如何使用正则表达式从字符串中解析某些数字?
问题描述
我有一个任务,我必须以这种方式从字符串中解析某些数字,
如果我将此字符串传递给方法,例如以下字符串:
*I bought 2 books in (2005), They were pretty good, but i didn't like the mention of god in it, 32(1-5), 214-443.
它应该打印版本:32,从 214 到 443 页
*have you read the book published in (2009), named The art of being selfish, look at page, 87, 104-105.
它应该打印版本:87,第 104 到 105 页
*Please take a look here in this link, you will find the, 10(3-4), 259-271.
它应该打印版本:10,从 259 到 271 页
*Someone help me here please in the look for it book, 5(1), 1-4
它应该打印版本:5,从 1 到 4 页
*Help needed (here), 8(4), 325-362.
它应该打印版本:8,从 325 到 362 页
I'm having trouble with the regex formatting since it is required.
解决方案
我在我的解决方案中写的
public static void main(String[] args) {
String testString = "Help needed (here), 8(4), 325-362.";
stringParser(testString);
}
static void stringParser(String string) {
List<String> pages = getPages(string);
String edition = getEdition(string);
System.out.println("Edition: " + edition +", pages from " + pages);
}
static List<String> getPages(String string) {
List<String> pages = new ArrayList<>();
Pattern ptr = Pattern.compile(">();(?<=\\w[,]\\s)[0-9]*");
Matcher match = ptr.matcher(string);
while (match.find()) {
pages.add(match.group());
}
return pages;
}
static String getEdition(String string) {
String edition = "0";
Pattern ptr = Pattern.compile("(?<=(\\d|[)])[,]\\s)\\d.*");
Matcher match = ptr.matcher(string);
if (match.find()) {
edition = match.group();
}
return edition;
}
使用所需句子链接到 Regex101 https://regex101.com/r/Cw5nG1/1
解决方案
我认为您需要几种解决方案。我认为需要一些不同的正则表达式。这是一个RegEx,它将有助于进一步的发展。
(\d+).*?(\b\d+\b).*?(\b\d+)
推荐阅读
- c# - 无法加载场景,因为它尚未添加到构建设置中
- excel - 即使单击了保存按钮,也会显示保存数据的消息框提示
- excel - VBA - Range(Selection, Selection.End(xlUp)).Select 正在更改活动单元格
- docker - 如何让 docker-compose 在 M1 芯片上工作?
- angular - 没有从(.ts)文件中获得单元测试(sepc.ts)中的填充数组
- r - 根据列值在 R 中添加行
- javascript - axios 请求无法读取未定义的属性
- sql - 未找到 db2 列或全局变量
- azure-iot-hub - 如果区域中断,我们可以手动从 Azure 门户 UI 故障转移到配对实例。我们可以以编程方式执行此步骤吗?
- python - XLXS文件的长字典(内部的元组值+不同长度)变量不起作用