我有这样的文字
Hello. @b this is text 1 #u user1
我想使用正则表达式来提取
This is text 1
user1
我的第一次尝试是检测@,#signs然后将这些文本记录到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
答案 0 :(得分: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