我如何表达“:"但不以"\"开头在Java正则表达式中? [英] How do I express ":" but not preceded by "\" in a Java regular expression?

查看:59
本文介绍了我如何表达“:"但不以"\"开头在Java正则表达式中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java正则表达式中表示不以"开头?例如,我只想搜索:",但仅当它不直接以"\"开头时才搜索.我该怎么办?

How can I express "not preceded by" in a Java regular expression? For example I would like to search for ":" but only when it is not directly preceded by "\". How can I do this?

推荐答案

使用后面是负数:

"(?<!\\\\):"

四个反斜杠的原因是:

  • 反斜杠是正则表达式中的特殊字符,因此您需要正则表达式 \\ 来匹配单个反斜杠.
  • 反斜杠必须在Java字符串中转义,因此上述每个反斜杠必须写为 \\ ,总共四个.
  • the backslash is a special character in regular expressions so you need the regular expression \\ to match a single backslash.
  • backslashes must be escaped in Java strings, so each of the above backslashes must be written as \\, giving a total of four.

示例代码:

Pattern pattern = Pattern.compile("(?<!\\\\):");
Matcher matcher = pattern.matcher("foo\\:x bar:y");
if (matcher.find()) {
    System.out.println(matcher.start());
}

输出:

10

这篇关于我如何表达“:"但不以"\"开头在Java正则表达式中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆