We help IT Professionals succeed at work.

Regular Expression in Java

Darren
Darren asked
on
Hi,

Can someone explain this pattern to me in detail?

(?:\*[FMC]\*)?([\d\.]+)(A)?

Thanks,

Darren
Comment
Watch Question

DarrenSenior Software Engineer
BRONZE EXPERT

Author

Commented:
The actual pattern is : "(?:\\*[FMC]\\*)?([\\d\\.]+)(A)?"
SILVER EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
(?:    -  Start of non-capturing group
\*     -  Literal star
[FMC]  -  Either an F, M, or C
\*     -  Literal star
)      -  End of non-capturing group
?      -  Make the entire group optional
(      -  Start of capture group 1
[\d\.] -  Either a digit ( \d ) or a period ( \.)
+      -  One or more of the the thing to the left (i.e. one or more digits or periods)
)      -  End of capture group 1
(      -  Start of capture group 2
A      -  Literal A
)      -  End of capture group 2
?      -  Make capture group 2 optional

Open in new window


The double backslashes are just to satisfy Java. Within string literals, Java can interpret special characters like newlines ( \n ) or tabs ( \t ). However, backslashes are special characters in regex as well. So you have to escape the backslash you want to use in the pattern to satisfy the compiler when it is looking at the string literal.
Nicely documented, kaufmed.

Darren - Are you posting because this pattern isn't working as intended?  It seems somewhat odd to define a highly-specific non-capture group, only to make it optional and begin capturing a far more general string of digits and periods.  Obviously, depends on the data you're working with and what you're trying to accomplish.  If this expression isn't working, you might consider posting some sample data and the desired result.
DarrenSenior Software Engineer
BRONZE EXPERT

Author

Commented:
Hi,

It's an expression written by someone previously and I've not had a lot of experience with regular expressions, at least not with any regularity. (What you don't use, you loose)

I have it working correctly now as I was able to update the last charachter to [AP] as it can be one of either of these. Apart from that I needed it explained fully as I've never heard of a non-capturing group and couldn't find anything on ?:

I'll have a look into why the first group in a non-capturing group when I get a chance.

Thanks,

Darren

Explore More ContentExplore courses, solutions, and other research materials related to this topic.