Java 中的正则表达式匹配器 \G(前一个匹配的结束)的示例会很好
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2708833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Examples of regex matcher \G (The end of the previous match) in Java would be nice
提问by Mister M. Bean
Do you haven any useful example of the boundary matcher "\G"`? Please give me some real world examples. Java source is appreciated. From "Mastering regular expressions. Jeffrey E. F. Friedl" I got an useful example parsing HTML but I am not sure how if a translation to Java is possible.
你有边界匹配器 "\G"` 的任何有用的例子吗?请给我一些真实世界的例子。Java 源代码表示赞赏。从“掌握正则表达式。Jeffrey EF Friedl”我得到了一个解析 HTML 的有用示例,但我不确定是否可以翻译成 Java。
回答by polygenelubricants
This is a regex-based solution to introduce thousand separators:
这是一个基于正则表达式的引入千位分隔符的解决方案:
String separateThousands(String s) {
return s.replaceAll(
"(?<=\G\d{3})(?=\d)" + "|" + "(?<=^-?\d{1,3})(?=(?:\d{3})+(?!\d))",
","
);
}
This will transform "-1234567890.1234567890"to "-1,234,567,890.1234567890".
这将转换"-1234567890.1234567890"为"-1,234,567,890.1234567890".
See also
也可以看看
- codingBat separateThousands using regex (and unit testing how-to)
- Explanation of how it works, and alternative regex that also uses
\G.
- Explanation of how it works, and alternative regex that also uses
- codingBat 使用正则表达式(和单元测试方法)分离千
- 解释它是如何工作的,以及也使用
\G.
- 解释它是如何工作的,以及也使用
This one is more abstract, but you can use \Gand fixed-length lookbehind to splita long string into fixed-width chunks:
这个更抽象,但你可以使用\G固定长度的lookbehind将split一个长字符串分成固定宽度的块:
String longline = "abcdefghijklmnopqrstuvwxyz";
for (String line : longline.split("(?<=\G.{6})")) {
System.out.println(line);
}
/* prints:
abcdef
ghijkl
mnopqr
stuvwx
yz
*/
You don't need regex for this, but I'm sure there are "real life" scenarios of something that is a variation of this technique.
您不需要为此使用正则表达式,但我确信存在这种技术变体的“现实生活”场景。
回答by JRL
Here's an example:
下面是一个例子:
Pattern p = Pattern.compile("\Gfoo");
Matcher m = p.matcher("foo foo");
String trueFalse = m.find() + ", " + m.find();
System.out.println(trueFalse);
Pattern p1 = Pattern.compile("foo");
Matcher m1 = p1.matcher("foo foo");
String trueTrue = m1.find() + ", " + m1.find();
System.out.println(trueTrue);

