-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcapture-groups-in-java.html
56 lines (50 loc) · 13.5 KB
/
capture-groups-in-java.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html><html lang="de-ch"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Capture Groups in Java - Finecloud</title><meta name="description" content="Capture Groups Im letzten Post haben wir einen kleinen Einstieg in Regex mit Java gemacht. Nun sehen wir uns an, wie man Regex Pattern in Java mittels Capture Groups anwenden kann: String regex = '(1[-.\\s])?(\\d{3}[-.\\s]?)(\\d{3}[-.\\s]?)\\d{4}'; String phoneNumber = '12.523.231.4234'; Pattern pat = Pattern.compile(regex); Matcher mat =…"><meta name="generator" content="Publii Open-Source CMS for Static Site"><link rel="stylesheet" href="https://www.finecloud.ch/media/plugins/syntaxHighlighter/prism-black.css"><link rel="canonical" href="https://www.finecloud.ch/capture-groups-in-java.html"><link rel="alternate" type="application/atom+xml" href="https://www.finecloud.ch/feed.xml"><link rel="alternate" type="application/json" href="https://www.finecloud.ch/feed.json"><meta property="og:title" content="Capture Groups in Java"><meta property="og:site_name" content="Finecloud"><meta property="og:description" content="Capture Groups Im letzten Post haben wir einen kleinen Einstieg in Regex mit Java gemacht. Nun sehen wir uns an, wie man Regex Pattern in Java mittels Capture Groups anwenden kann: String regex = '(1[-.\\s])?(\\d{3}[-.\\s]?)(\\d{3}[-.\\s]?)\\d{4}'; String phoneNumber = '12.523.231.4234'; Pattern pat = Pattern.compile(regex); Matcher mat =…"><meta property="og:url" content="https://www.finecloud.ch/capture-groups-in-java.html"><meta property="og:type" content="article"><link rel="shortcut icon" href="https://www.finecloud.ch/media/website/finecloud.png" type="image/png"><link rel="stylesheet" href="https://www.finecloud.ch/assets/css/style.css?v=39da73365516a098a9b73b721fc970e2"><script type="application/ld+json">{"@context":"http://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.finecloud.ch/capture-groups-in-java.html"},"headline":"Capture Groups in Java","datePublished":"2022-07-14T06:02","dateModified":"2022-07-14T06:35","description":"Capture Groups Im letzten Post haben wir einen kleinen Einstieg in Regex mit Java gemacht. Nun sehen wir uns an, wie man Regex Pattern in Java mittels Capture Groups anwenden kann: String regex = '(1[-.\\\\s])?(\\\\d{3}[-.\\\\s]?)(\\\\d{3}[-.\\\\s]?)\\\\d{4}'; String phoneNumber = '12.523.231.4234'; Pattern pat = Pattern.compile(regex); Matcher mat =…","author":{"@type":"Person","name":"Finecloud","url":"https://www.finecloud.ch/authors/finecloud/"},"publisher":{"@type":"Organization","name":"Finecloud"}}</script><meta name="google-site-verification" content="seFY9U12uiEq5U3_MyZiX6XWzk0AVFl9zITr2ZKsytY"></head><body><div class="site-container"><header class="top" id="js-header"><a class="logo" href="https://www.finecloud.ch/">Finecloud</a><nav class="navbar js-navbar"><button class="navbar__toggle js-toggle" aria-label="Menu" aria-haspopup="true" aria-expanded="false"><span class="navbar__toggle-box"><span class="navbar__toggle-inner">Menu</span></span></button><ul class="navbar__menu"><li><a href="https://www.finecloud.ch/" target="_self">Blog</a></li><li><a href="https://www.finecloud.ch/tags/" target="_self">Tags</a></li></ul></nav><div class="search"><div class="search__overlay js-search-overlay"><div class="search__overlay-inner"><form action="https://www.finecloud.ch/search.html" class="search__form"><input class="search__input js-search-input" type="search" name="q" placeholder="search..." aria-label="search..." autofocus="autofocus"></form><button class="search__close js-search-close" aria-label="Close">Close</button></div></div><button class="search__btn js-search-btn" aria-label="Search"><svg role="presentation" focusable="false"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#search"/></svg></button></div></header><main><article class="post"><div class="hero"><figure class="hero__image hero__image--overlay"><img src="https://www.finecloud.ch/media/website/download.jpg" srcset="https://www.finecloud.ch/media/website/responsive/download-xs.jpg 300w, https://www.finecloud.ch/media/website/responsive/download-sm.jpg 480w, https://www.finecloud.ch/media/website/responsive/download-md.jpg 768w, https://www.finecloud.ch/media/website/responsive/download-lg.jpg 1024w, https://www.finecloud.ch/media/website/responsive/download-xl.jpg 1360w, https://www.finecloud.ch/media/website/responsive/download-2xl.jpg 1600w" sizes="100vw" loading="eager" alt=""></figure><header class="hero__content"><div class="wrapper"><div class="post__meta"><time datetime="2022-07-14T06:02">Juli 14, 2022</time></div><h1>Capture Groups in Java</h1></div></header></div><div class="wrapper post__entry"><div class="post__toc"><h3>Table of Contents</h3><ul><li><a href="#mcetoc_1g7tfqiu92l">Capture Groups</a></li><li><a href="#mcetoc_1g7tfr24a2o">Not Capture Groups</a></li><li><a href="#mcetoc_1g7tfqiu92m">Named Capture Groups</a></li></ul></div><h2 id="mcetoc_1g7tfqiu92l">Capture Groups</h2><p><a href="https://www.finecloud.ch/einstieg-in-regex-mit-java.html" rel="nofollow">Im letzten Post</a> haben wir einen kleinen Einstieg in Regex mit Java gemacht. Nun sehen wir uns an, wie man Regex Pattern in Java mittels Capture Groups anwenden kann:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> String regex = <span class="hljs-string" style="color: #6a8759;">"(1[-.\\s])?(\\d{3}[-.\\s]?)(\\d{3}[-.\\s]?)\\d{4}"</span>;
String phoneNumber = <span class="hljs-string" style="color: #6a8759;">"12.523.231.4234"</span>;
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(phoneNumber);
<span class="hljs-keyword" style="color: #cc7832;">if</span> (mat.matches()){
//System.out.format("entire String: %s\n", mat.group(0));
System.out.format("Country Code: %s\n", mat.group(2));
System.out.format("Area Code: %s\n", mat.group(4));
System.out.format("Exchange Code: %s\n", mat.group(6));
System.out.format("Line number Code: %s\n", mat.group(7));
}</pre><p>Damit können wir nun die einzelnen Nummern-Teile extrahieren und separat behandeln:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;">Country Code: 12
Area Code: 523
Exchange Code: 231
Line number Code: 4234</pre><h2 id="mcetoc_1g7tfr24a2o">Not Capture Groups</h2><p>Im Beispiel oben werden die Klammern fortlaufend nummeriert, jede Klammer wird von links nach rechts aufsteigend nummeriert, dabei werden auch die embeded Gruppen mitgezählt. Das hat den Nachteil das es etwas unübersichtlich wird, welche Nummer hat nun die Klammer in der Mitte. Dabei interessieren uns ja eigentlich immer nur die embeded Gruppen. Das können wir optimieren, indem wir bei den Klammern welche uns nicht interessieren ein '?:' direkt nach dem Öffnen der Klammer angeben. Das bedeutet dann soviel wir <em>not Capture Group</em>. Damit wird für die Klammern keine Gruppennummer vergeben:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> String regex = <span class="hljs-string" style="color: #6a8759;">"(?:(\\d{1,2})[-.\\s])?(?:(\\d{3})[-.\\s]?)(?:(\\d{3})[-.\\s]?)(\\d{4})"</span>;
String phoneNumber = <span class="hljs-string" style="color: #6a8759;">"12.523.231.4234"</span>;
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(phoneNumber);
<span class="hljs-keyword" style="color: #cc7832;">if</span> (mat.matches()){
<span class="hljs-comment" style="color: grey;">//System.out.format("entire String: %s\n", mat.group(0));</span>
System.out.format(<span class="hljs-string" style="color: #6a8759;">"Country Code: %s\n"</span>, mat.group(<span class="hljs-number" style="color: #6897bb;">1</span>));
System.out.format(<span class="hljs-string" style="color: #6a8759;">"Area Code: %s\n"</span>, mat.group(<span class="hljs-number" style="color: #6897bb;">2</span>));
System.out.format(<span class="hljs-string" style="color: #6a8759;">"Exchange Code: %s\n"</span>, mat.group(<span class="hljs-number" style="color: #6897bb;">3</span>));
System.out.format(<span class="hljs-string" style="color: #6a8759;">"Line number Code: %s\n"</span>, mat.group(<span class="hljs-number" style="color: #6897bb;">4</span>));
}</pre><h2 id="mcetoc_1g7tfqiu92m">Named Capture Groups</h2><p>Noch mehr Optimieren können wir das mit Named Capture Groups:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> String regex = <span class="hljs-string" style="color: #6a8759;">"(?:(?<countryCode>\\d{1,2})[-.\\s])?(?:(?<areaCode>\\d{3})[-.\\s]?)(?:(?<exchangeCode>\\d{3})[-.\\s]?)(?<lineNumber>\\d{4})"</span>;
String phoneNumber = <span class="hljs-string" style="color: #6a8759;">"12.523.231.4234"</span>;
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(phoneNumber);
<span class="hljs-keyword" style="color: #cc7832;">if</span> (mat.matches()){
<span class="hljs-comment" style="color: grey;">//System.out.format("entire String: %s\n", mat.group(0));</span>
System.out.format(<span class="hljs-string" style="color: #6a8759;">"Country Code: %s\n"</span>, mat.group(<span class="hljs-string" style="color: #6a8759;">"countryCode"</span>));
System.out.format(<span class="hljs-string" style="color: #6a8759;">"Area Code: %s\n"</span>, mat.group(<span class="hljs-string" style="color: #6a8759;">"areaCode"</span>));
System.out.format(<span class="hljs-string" style="color: #6a8759;">"Exchange Code: %s\n"</span>, mat.group(<span class="hljs-string" style="color: #6a8759;">"exchangeCode"</span>));
System.out.format(<span class="hljs-string" style="color: #6a8759;">"Line number Code: %s\n"</span>, mat.group(<span class="hljs-string" style="color: #6a8759;">"lineNumber"</span>));
}</pre><p> </p></div><footer class="wrapper post__footer"><p class="post__last-updated">This article was updated on Juli 14, 2022</p><ul class="post__tag"><li><a href="https://www.finecloud.ch/tags/java/">java</a></li><li><a href="https://www.finecloud.ch/tags/java-basics/">java basics</a></li><li><a href="https://www.finecloud.ch/tags/regex/">regex</a></li><li><a href="https://www.finecloud.ch/tags/softwareentwicklung/">software development</a></li></ul><div class="post__share"></div></footer></article><nav class="post__nav"><div class="post__nav-inner"><div class="post__nav-prev"><svg width="1.041em" height="0.416em" aria-hidden="true"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#arrow-prev"/></svg> <a href="https://www.finecloud.ch/einstieg-in-regex-mit-java.html" class="post__nav-link" rel="prev"><span>Previous</span> Einstieg in Regex mit Java</a></div><div class="post__nav-next"><a href="https://www.finecloud.ch/monitor-proxmox-mit-grafana-und-prometheus.html" class="post__nav-link" rel="next"><span>Next</span> Monitor Proxmox mit Grafana und Prometheus </a><svg width="1.041em" height="0.416em" aria-hidden="true"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#arrow-next"/></svg></div></div></nav><div class="post__related related"><div class="wrapper"><h2 class="h5 related__title">You should also read:</h2><article class="related__item"><div class="feed__meta"><time datetime="2022-05-26T14:07" class="feed__date">Mai 26, 2022</time></div><h3 class="h1"><a href="https://www.finecloud.ch/java-collection-iteratoren.html">Java Collection Iteratoren</a></h3></article><article class="related__item"><div class="feed__meta"><time datetime="2022-05-26T13:28" class="feed__date">Mai 26, 2022</time></div><h3 class="h1"><a href="https://www.finecloud.ch/java-collection-sets.html">Java Collection Sets</a></h3></article><article class="related__item"><div class="feed__meta"><time datetime="2022-05-26T13:19" class="feed__date">Mai 26, 2022</time></div><h3 class="h1"><a href="https://www.finecloud.ch/java-collection-listen.html">Java Collection Listen</a></h3></article></div></div></main><footer class="footer"><div class="footer__copyright"><p>Powered by Publii</p></div><button onclick="backToTopFunction()" id="backToTop" class="footer__bttop" aria-label="Back to top" title="Back to top"><svg><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#toparrow"/></svg></button></footer></div><script>window.publiiThemeMenuConfig = {
mobileMenuMode: 'sidebar',
animationSpeed: 300,
submenuWidth: 'auto',
doubleClickTime: 500,
mobileMenuExpandableSubmenus: true,
relatedContainerForOverlayMenuSelector: '.top',
};</script><script defer="defer" src="https://www.finecloud.ch/assets/js/scripts.min.js?v=6ca8b60e6534a3888de1205e82df8528"></script><script>var images = document.querySelectorAll('img[loading]');
for (var i = 0; i < images.length; i++) {
if (images[i].complete) {
images[i].classList.add('is-loaded');
} else {
images[i].addEventListener('load', function () {
this.classList.add('is-loaded');
}, false);
}
}</script><script defer="defer" src="https://www.finecloud.ch/media/plugins/syntaxHighlighter/prism.js"></script></body></html>