英文:
Regular Expression for one of the use case in java, starting from DANNO and ending with integer
问题
我正在尝试创建一个正则表达式来从字符串中获取数字。我使用了 https://regexr.com/ 并得出了以下正则表达式 (DANNO)[^0-9]*[0-9]*
这在他们的控制台上运行良好,但当我尝试在我的 Java 代码中使用时,对于某些情况它只是返回 DANNO。
以下是一些示例字符串及其预期结果:
N. DANNO: 1234567890 => DANNO: 1234567890
DANNO N° 1234567890 => DANNO N° 1234567890
ORDINE N 1234567890 N DANNO 1234567890 N CLIENTE 123456 => DANNO 1234567890
N°DANNO1234567890 => DANNO1234567890
DANNON°1234567890 => DANNON°1234567890
英文:
I am trying to create one regex to get a number from string. I used https://regexr.com/ and cam up with the following regex (DANNO)[^0-9]*[0-9]*
this works fine on their console but when I am trying to use in my java code it's just giving me DANNO for some of the cases.
Some of the sample strings are below with the expected result:
N. DANNO: 1234567890 => DANNO: 1234567890
DANNO N° 1234567890 => DANNO N° 1234567890
ORDINE N 1234567890 N DANNO 1234567890 N CLIENTE 123456 => DANNO 1234567890
N°DANNO1234567890 => DANNO1234567890
DANNON°1234567890 => DANNON°1234567890
</details>
# 答案1
**得分**: 0
```java
public static void main(String[] args) throws ParseException {
final String regex = "(DANNO)[^0-9]*[0-9]*";
final String string = "N. DANNO: 1234567890\n"
+ "DANNO N° 1234567890\n"
+ "ORDINE N 1234567890 N DANNO 1234567890 N CLIENTE 123456\n"
+ "N°DANNO1234567890\n"
+ "DANNON°1234567890";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0)); //Prints full search result
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i)); //Prints DANO
}
}
}
输出:
Full match: DANNO: 1234567890
Group 1: DANNO
Full match: DANNO N° 1234567890
Group 1: DANNO
Full match: DANNO 1234567890
Group 1: DANNO
Full match: DANNO1234567890
Group 1: DANNO
Full match: DANNON°1234567890
Group 1: DANNO
英文:
public static void main(String[] args) throws ParseException {
final String regex = "(DANNO)[^0-9]*[0-9]*";
final String string = "N. DANNO: 1234567890\n"
+ "DANNO N° 1234567890\n"
+ "ORDINE N 1234567890 N DANNO 1234567890 N CLIENTE 123456\n"
+ "N°DANNO1234567890\n"
+ "DANNON°1234567890";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0)); //Prints full serach result
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i)); //Prints DANO
}
}
}
output
Full match: DANNO: 1234567890
Group 1: DANNO
Full match: DANNO N° 1234567890
Group 1: DANNO
Full match: DANNO 1234567890
Group 1: DANNO
Full match: DANNO1234567890
Group 1: DANNO
Full match: DANNON°1234567890
Group 1: DANNO
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论