0

I have this regex expression:

String patt = "(\\w+?)(:|<|>)(\\w+?),"; 
Pattern pattern = Pattern.compile(patt);
Matcher matcher = pattern.matcher(search + ",");

I am able to match a string like

search = "firstName:Giorgio"

But I'm not able to match string like

search = "email:giorgio.rossi@libero.it"

or

search = "dataregistrazione:27/10/2016"

How I should modify the regex expression in order to match these strings?

Divyang Desai
  • 7,483
  • 13
  • 50
  • 76

3 Answers3

0

You may use

String pat = "(\\w+)[:<>]([^,]+)"; // Add a , at the end if it is necessary

See the regex demo

Details:

  • (\w+) - Group 1 capturing 1 or more word chars
  • [:<>] - one of the chars inside the character class, :, <, or >
  • ([^,]+) - Group 2 capturing 1 or more chars other than , (in the demo, I added \n as the demo input text contains newlines).
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

You can use regex like this:

public static void main(String[] args) {
    String[] arr = new String[]{"firstName:Giorgio", "email:giorgio.rossi@libero.it", "dataregistrazione:27/10/2016"};
    String pattern = "(\\w+[:|<|>]\\w+)|(\\w+:\\w+\\.\\w+@\\w+\\.\\w+)|(\\w+:\\d{1,2}/\\d{1,2}/\\d{4})";
    for(String str : arr){
        if(str.matches(pattern))
            System.out.println(str);
    }
}

output is:

firstName:Giorgio
email:giorgio.rossi@libero.it
dataregistrazione:27/10/2016

But you have to remember that this regex will work only for your format of data.
To make up the universal regex you should use RFC documents and articles (i.e here) about email format.
Also this question can be useful.

Hope it helps.

Community
  • 1
  • 1
Michał Szewczyk
  • 7,540
  • 8
  • 35
  • 47
0

The Character class \w matches [A-Za-z0-9_]. So kindly change the regex as (\\w+?)(:|<|>)(.*), to match any character from : to ,.

Or mention all characters that you can expect i.e. (\\w+?)(:|<|>)[@.\\w\\/]*, .

CS_noob
  • 557
  • 1
  • 6
  • 18