[英]Regular expression to find characters between ##
我有以下文字
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());
}
}
}
(.*?[^\#])|(#.*#)
試試這個正則表達式
這似乎是您要查找的內容:
([^#]+|#[^#]+#)
或者,如果您要修剪空白:
\s*([^#]+?(?=\s*#|$)|#[^#]+#)
另一種模式可以修剪結果
(#[^#]+#|[^#]+)(?:\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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.