Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use groups in regular expressions in java

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use groups in regular expressions in java. It is very detailed and has a certain reference value. Friends who are interested must read it!

A group is a regular expression divided by parentheses and can refer to a group according to its number. The group number 0 represents the entire expression, the group number 1 represents the group expanded by the first parenthesis from left to right, and so on.

For example:

There are three groups in A (B (CD)) E: group 0 is ABCDE, group 1 is BCD, and group 2 is CD.

The Matcher object provides a series of methods to get group-related information:

Method function

Public int groupCount () returns the number of packets in the pattern of the matcher Group 0 not included public String group () returns group 0 (whole match) public String group (int I) returns the specified group number public int start (int group) during the previous matching operation returns the starting index public int end (int group) of the group found in the previous matching operation returns the value of the last character index plus one of the group found in the previous matching operation

Example:

Import java.util.regex.Matcher;import java.util.regex.Pattern;public class GroupsDemo {static public final String POEM= "Twas brilling, and the slithy toves\ n" + "Did gyre and gimble in the wabe.\ n" + "All mimsy were the borogoves,\ n" + "And the mome raths outgrabe.\ n" Public static void main (String [] args) {/ * * Patten.MULTILINE represents a multiline pattern. In multiline mode, the expressions ^ and $match the beginning and end of a line, respectively, or match the beginning and end of the input string *\ S+ represents a non-space character more than once, and s + represents a space character more than once to match the last three characters of each line. * / Matcher m=Pattern.compile ("(\\ S+)\\ s + ((\\ S+)\\ s + (\\ S+)) $", Pattern.MULTILINE) .matcher (POEM); while (m.find ()) {for (int I = 0; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report