1

我正在尝试提出一个简单的正则表达式,它将查找第一个“:”,然后是未知数量的字符串,直到一个“。” 找到并返回其间的字符串。

例子

test example:IWANTTHISBACK. [8909] test

结果

IWANTTHISBACK

任何帮助都会很棒

4

3 回答 3

3

我正在尝试提出一个简单的正则表达式,它将查找第一个“:”,然后是未知数量的字符串,直到一个“。” 找到并返回其间的字符串。

你基本上回答了你自己的问题。如果你把它翻译成正则表达式,它看起来相当简单:

为了第一 ':'

:

后跟未知数量的字符串,直到出现“。”

[^.]* matches all non dots and stops at first dot.

因此,如果您将所有这些写在一起:

:([^.]*)

反向引用$1将有你的字符串。

于 2012-05-24T11:24:30.433 回答
2

尝试这个

(?<=:)([^\.]*?)(?=\.)

解释

<!--
(?<=:)([^\.]*?)(?=\.)

Options: case insensitive

Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=:)»
   Match the character “:” literally «:»
Match the regular expression below and capture its match into backreference number 1 «([^\.]*?)»
   Match any character that is NOT a . character «[^\.]*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\.)»
   Match the character “.” literally «\.»
-->
于 2012-05-24T11:23:02.413 回答
0

在 Java 中

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile(":([^.]*)\\.");
        Matcher matcher = pattern.matcher("test example:IWANTTHISBACK. :abc.[8909] test");
        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

输出:

IWANTTHISBACK
于 2012-05-24T11:24:49.623 回答