正则表达式删除除特定格式之外的所有内容

时间:2014-08-22 08:48:50

标签: java regex

我有这样的文字:

  

ASD.123.av.234.X_975.dfgdfg

我希望将其归结为:

  

.123.234。

 "\\.[0-9]+\\."

这表示我当前选择.number的模式。但负面的前瞻对我没有用:"(?!^\\.[0-9]+\\.)"你们有没有想过如何实现这个目标?

4 个答案:

答案 0 :(得分:1)

只需尝试使用Lookaround选择.number.

即可
  

环视实际匹配字符,但随后放弃匹配,仅返回结果:匹配或不匹配

(?<=\.)\d+(?=\.)

Online demo

模式说明:

  (?<=                     look behind to see if there is:
    \.                       '.'
  )                        end of look-behind
  \d+                      digits (0-9) (1 or more times)
  (?=                      look ahead to see if there is:
    \.                       '.'
  )                        end of look-ahead

示例代码:

String str = "ASD.123.av.234.X_975.dfgdfg";
Pattern p = Pattern.compile("(?<=\\.)\\d+(?=\\.)");
Matcher m = p.matcher(str);
while (m.find()) {
    System.out.println(m.group());
}

输出:

123
234

你的正则表达式是什么意思?

  (?!                      look ahead to see if there is not: 
    ^                        the beginning of the string
    \.                       '.'
    [0-9]+                   any character of: '0' to '9' (1 or more times )
     \.                       '.'
   )                        end of look-ahead

问题在于^断言字符串的开头。

答案 1 :(得分:0)

  (?=.*?\.\d+\..*?).*?(.\d+.).*?

你可以试试这个。它采用积极的前瞻。

http://regex101.com/r/dK7kR5/1

答案 2 :(得分:0)

试试这个正则表达式:(\.[0-9]+?\.)(?:.*?\.([0-9]+?\.))+

在上面的输出中,您似乎不希望.123..234..123.234.这个正则表达式实现了这一点。它没有前瞻性。

Regex Demo

答案 3 :(得分:0)

试试下面的正则表达式。它会为你提供.number.的所有组。你不得不稍后再和那些人约会。

(\.[0-9]+\.)+

尝试此网站进行进一步测试: http://www.regexplanet.com/advanced/java/index.html