user2866792
user2866792

Reputation: 1

regular expression in java for first three letters in a sentence

how to write an regular expression in java for the sentence that is similar below and that should match only first three characters of the sentence

ins(clear(icl>remove>do,plf>thing,obj>thing,ins>thing).@entry.@past,evidence(icl>indication>thing))

i tried this code but it also matches clear,evidence in the sentence....

String pattern2="[-a-z0-9R:._-`&=*'`~\"\\+[\\s]]+[\\(]";  

Pattern r2 = Pattern.compile(pattern2);
Matcher m2 = r2.matcher(line);


 while (m2.find()) 
 {
     rel = m2.group();
     rel = rel.substring(0, rel.length()-1).trim();                 
     System.out.println("The relation are " + rel); 
 }

Upvotes: 0

Views: 1406

Answers (4)

Pshemo
Pshemo

Reputation: 124225

If you want to only get match from start of the line you can add ^ at start of your regex (before [).

If you want to be sure that matched part before ( will have 3 characters don't use ..]+ but ..]{3}.

Also if you want to just check if some characters are after interesting part but you don't want to include them use look-ahead mechanism (?=...) like in your case (?=[\\(]) or simpler (?=[(]) - there is no need to escape ( with \\ and []at the same time.

So maybe change your pattern to

String pattern2 = "^[-a-z0-9R:._-`&=*'`~\"+\\s]{3}(?=[(])";

Also I am not sure if _-` is what you mean since it will create range of characters between _ and `

Upvotes: 1

Bohemian
Bohemian

Reputation: 425033

This regex matches the first 3 chars:

^...

Upvotes: 1

Bax
Bax

Reputation: 4476

I guess you should remove firstly all non-letters

String result = string.replaceAll("[^a-zA-Z]", "");

And then just taking first three symbols :

result.substring(0, 3)

Upvotes: 1

xagyg
xagyg

Reputation: 9711

This...

String pattern2="^[^\\(]+";

Upvotes: 0

Related Questions