Johnydep
Johnydep

Reputation: 6277

regex in java, making a search for particular string pattern?

i am not much familiar with regex expressions use in Java. If i have a String this/is/a/file!/path

now with substring and indexOf i can find the name file appearing inbetween / and ! but i am pretty sure such tasks must be much easier using regexes.

Can someone give me an example for doing so using regex expressions?

Upvotes: 0

Views: 1042

Answers (4)

Sumit Jain
Sumit Jain

Reputation: 1528

You can create a Pattern Object with a regular expression and then create a matcher object from it to parse your String.

String regex = ".*/(.*)!";

Pattern p = Pattern.compile (regex);

Matcher m = p.matcher(StringToBeMatched);

if (m.find()) {

    String filename = m.group (1);
}

Upvotes: 0

Don
Don

Reputation: 1144

Another way is to use Pattern and Matcher. Here you can use groups and more complex operations

Pattern pattern = Pattern.compile(yourRegex);
Matcher matcher = pattern.matcher(yourText);
while(matcher.find()) {
   System.out.println(matcher.group(1));
}

Take a look at

Matcher : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html

Pattern : http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

Regex in Java : http://docs.oracle.com/javase/tutorial/essential/regex/

Upvotes: 3

Vinze
Vinze

Reputation: 2539

somthing as .*/([^!]*)!.* should do this... then you can use a matcher to find the 1st group (the part between parenthesis, the 0th group is the whole match)

I didn't test this solution...

Upvotes: 0

fivedigit
fivedigit

Reputation: 18682

The simplest way of using them in Java is by using the String.matches method:

boolean matches = "abc".matches("[a-z]+");

That would yield true.

The second way of doing it is useful if you have to use a specific regex pattern a lot of times. You can compile it and reuse it:

Pattern pattern = Pattern.compile("[a-z]+");
Matcher matcher = pattern.matcher("abc");
boolean matches = matcher.matches();

Upvotes: -1

Related Questions