简体   繁体   English

在java中使用正则表达式从字符串中提取特定数字

[英]Extract a particular number from a string using regex in java

Here is my string这是我的字符串

INPUT:输入:

22 TIRES (2 defs)

1 AP(PEAR + ANC)E (CAN anag)

6 CHIC ("SHEIK" hom)

EXPECTED OUTPUT:预期产出:

22 TIRES

1 APPEARANCE

6 CHIC

ACTUAL OUTPUT :实际输出:

TIRES

APPEARANCE

CHIC

I tried using below code and got the above output.我尝试使用下面的代码并得到上面的输出。

String firstnames =a.split(" \\(.*")[0].replace("(", "").replace(")", "").replace(" + ",
                        "");

Any idea of how to extract along with the numbers ?知道如何提取数字吗? I don't want the numbers which are after the parentheses like in the input " 22 TIRES (2 defs)".我不想要输入“22 TIRES (2 defs)”中括号后的数字。 I need the output as "22 TIRES" Any help would be great !!我需要输出为“22 TIRES”任何帮助都会很棒!!

I would use a single replaceAll function.我会使用一个 replaceAll 函数。

str.replaceAll("\\s+\\(.*|\\s*\\+\\s*|[()]", "");

DEMO演示

  • \\\\s+\\\\(.* , this matches a space and and the following ( characters plus all the remaining characters which follows this pattern. So (CAN anag) part in your example got matched. \\\\s+\\\\(.* ,这匹配一个空格和以下(字符加上遵循此模式的所有剩余字符。因此,您示例中的(CAN anag)部分匹配。

  • \\\\s*\\\\+\\\\s* matches + along with the preceding and following spaces. \\\\s*\\\\+\\\\s*匹配+以及前后空格。

  • [()] matches opening or closing brackets. [()]匹配左括号或右括号。

  • Atlast all the matched chars are replaced by empty string. Atlast 所有匹配的字符都被替换为空字符串。

I am doing it bit differently我做的有点不同

String line = "22 TIRES (2 defs)\n\n1 AP(PEAR + ANC)E (CAN anag)\n\n6 CHIC (\"SHEIK\" hom)"; 
String pattern = "(\\d+\\s+)(.*)\\(";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
while (m.find()) {
    String tmp = m.group(1) + m.group(2).replaceAll("[^\\w]", "");
    System.out.println(tmp);
}

Ideone Demo Ideone 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM