Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have String like:

Java
<pre>1H|\^&|||PACMAN|||||PSM||P||20170118062717|


And I want to extract data H, PACMAN, PSM, P and 20170118062717

What can be the Regular Expression for this String?

What I have tried:

This is how I am trying:

Java
(?:^(R)\|(\d+)\|\^*([^|]*)\|([^|]*)\|(?:([^|]*)\|)?.*$)|(?:^(P)\|(\d+)\|\|(\d+).*$)
Posted
Updated 20-Jan-17 7:36am

I'd start with:
(?<=|)\w+
Which would retrieve:
1H
PACMAN
PSM
P
20170118062717
And manually discard the leading zero, or use
([a-zA-Z]+|\d{2,})(?=|)



That's nice. Can I get these values in groups?

To use it as groups, you would need to specify the exact layout - which isn't difficult, but does depend on your data. If the sample is representative and you want groups for the "filled columns" only, but columns are delimited by "|" characters, then try:
^\d(\w+)(?:|.*?){3}(\w+)(?:|.*?){5}(\w+)(?:|.*?)(\w+)(?:|.*?)(\w+)|$
Should extract the fields you are interested in as numbered groups within a single match.
 
Share this answer
 
v2
Comments
FaizanMubasher 20-Jan-17 7:46am    
That's nice. Can I get these values in groups? Group1 ->H, Group2 -> PACMAN etc
OriginalGriff 20-Jan-17 8:05am    
Answer updated
FaizanMubasher 20-Jan-17 8:22am    
Yup! That worked. Thanks.
OriginalGriff 20-Jan-17 8:27am    
You're welcome!
If you original string is
1H|\^&|||PACMAN|||||PSM||P||20170118062717|
and you want to extract
H, PACMAN, PSM, P and 20170118062717
from it, the regex pattern will have to match either:
1. one or more letters
[a-zA-Z]+
or
2. a numeric string of 2 digits and above
[0-9]{2,}
Putting together, that would be
[a-zA-Z]+|[0-9]{2,}
 
Share this answer
 
You already got a solution, so just a few link to tools to help you build and debug your RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 
Comments
FaizanMubasher 23-Jan-17 1:26am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900