Labeo
Labeo

Reputation: 6349

How to use regex in java to match a word

I am trying to match a word (Source Ip) where each letter can be small or capital letter so i have wrote a regex pattern down but my m.find() is showing false even for Correct Match...

Is there any wrong in my regex pattern or the way I have written is wrong?

  String word = "Source Ip";
    String pattern = "[S|s][O|o][U|u][R|r][C|c][E|e]\\s*[I|i][P|p]";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(word);
    System.out.println(m.find());

Upvotes: 2

Views: 113

Answers (4)

wumpz
wumpz

Reputation: 9131

This solution has the problem of accepting sourceip as well.

source\s*ip

Regular expression visualization

Debuggex Demo

Therefore the correct answer should be

source\s+ip

Regular expression visualization

Debuggex Demo

to force the presence of at least one whitespace between the two words.

To use this expression in Java you have to escape the backslash and use something like:

Pattern.compile("source\\s+ip", Pattern.CASE_INSENSITIVE);

Upvotes: 0

Mena
Mena

Reputation: 48404

You don't need to alternate all letters between upper case and lowercase (note, as mentioned by others, the character class idiom does not require | to alternate - adding it between square brackets will also match the | literal).

You can parametrize your Pattern initialization with the Pattern.CASE_INSENSITIVE flag (alternative inline usage would be (?i) before your pattern representation).

For instance:

Pattern.compile("(?i)source\\s*ip");

... or ...

Pattern.compile("source\\s*ip", Pattern.CASE_INSENSITIVE);

Note

Flag API here.

Upvotes: 5

Dexter Whelan
Dexter Whelan

Reputation: 454

if you really want to use regex though for some reason and not pattern. methods then this regex should suit your needs and it works just fine in java for me

 [s|S][o|O][U|u][r|R][c|C][e|E][ ]*[i|I][p|P]

your case of using

\\s*

won't identify spaces however this will

 \s*

you had one slash too many :)

EDIT: I demonstrate my ignorance, after checking regexpal I was wrong, [sS] is better than [s|S] [sS][oO][Uu][rR][cC][eE][ ]*[iI][pP] thank you Pshemo and yes i completely forgot about escaping characters Mena thank you for pointing that out for me

Upvotes: -2

Jens
Jens

Reputation: 69440

You can simple use

String pattern = "SOURCE\\s*IP";
Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);

Pattern.CASE_INSENSITIVE will make the matching case insensitive.

Upvotes: 7

Related Questions