我的文字如下
Here is some text #variable name# that goes very long with #another variable name# and
goes longer #another another variable# and some more.
我想编写一个正则表达式,将此文本拆分为像这样的组
Group 1: Here is some text
Group 2: #variable name#
Group 3: that goes very long with
Group 4: #another variable name#
Group 5: and goes longer
Group 6: #another another variable#
Group 7: and some more
我的尝试很糟糕。我无法理解这件事
(.*?)*(#.*#)*(.*?)*
此外,这需要在Java中工作..如下所示
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.*;
public class Test {
public static void main(String[] args) {
Pattern pattern = compile("(([^#]+)|(#[^#]+#)) ");
String string="Here is some text #variable name# that goes very long with #another variable name# and " +
"goes longer #another another variable# and some more.";
Matcher matcher = pattern.matcher(string);
while(matcher.find()){
System.out.println(matcher.group());
}
}
}
答案 0 :(得分:0)
答案 1 :(得分:0)
答案 2 :(得分:0)
(.*?[^\#])|(#.*#)
试试这个正则表达式
答案 3 :(得分:0)
这似乎就是你要找的东西:
([^#]+|#[^#]+#)
或者如果你想修剪白色空间:
\s*([^#]+?(?=\s*#|$)|#[^#]+#)
答案 4 :(得分:0)
还有一个模式可以修剪结果
(#[^#]+#|[^#]+)(?:\s|$)
( Capturing Group \1
# "#"
[^#] Character not in [^#]
+ (one or more)(greedy)
# "#"
| OR
[^#] Character not in [^#]
+ (one or more)(greedy)
) End of Capturing Group \1
(?: Non Capturing Group
\s <whitespace character>
| OR
$ End of string/line
) End of Non Capturing Group