1

我有这样的文字

Hello. @b this is text 1 #u user1

我想用正则表达式提取

This is text 1
user1

我的第一次尝试是检测@,# 符号,然后将这些文本记录到 StringBuilder 中。但是,这是一个 EditText,用户可以删除一些字符,而我必须从 stringbuilder 中删除它。最后,它变得越来越复杂,所以我决定找到另一个解决方案。

我的问题是:当命令(@b,#u,#b,@u)可用时,如何提取这些文本?例如:

Hello. @b this is text 1 => [This is text 1]
Hello. @b this is text 1 #u user1 => [This is text 1] [user1]
Hello. @u user1 => [user1]

我的第二次尝试:

 Pattern pattern = Pattern.compile("@b (.+) #u (.+)");
 Matcher mat = pattern.matcher(charSequence);
 while (mat.find()) {
      Logger.write("Matcher "+mat.group(1));
 }

但它只适用于特定情况@b 和#u

4

1 回答 1

1

那个正则表达式是

Pattern regex = Pattern.compile("(?<=[@#][bu]\\s)(?:(?![@#][bu]).)*");

解释:

(?<=    # Assert that this can be matched before the current position:
 [@#]   # an "@" or a "#"
 [bu]   # a "b" or a "u"
 \\s    # a whitespace character
)       # End of lookbehind assertion
(?:     # Then match...
 (?!    #  (as long as we're not at the start of the sequence
  [@#]  #  "@" or "#"
  [bu]  #  and "b" or "u"
 )      #  End of lookahead)
 .      # any character
)*      # any number of times
于 2013-06-04T05:48:28.603 回答