简体   繁体   English

java中的正则表达式,搜索特定的字符串模式?

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

i am not much familiar with regex expressions use in Java. 我对Java中使用的正则表达式不太熟悉。 If i have a String this/is/a/file!/path 如果我有一个字符串this/is/a/file!/path

now with substring and indexOf i can find the name file appearing inbetween / and ! 现在使用substringindexOf我可以找到出现在/和之间的名称文件! 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? 有人可以使用正则表达式给我一个例子吗?

Another way is to use Pattern and Matcher. 另一种方法是使用Pattern和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 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 模式: 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/ Java中的正则表达式: http//docs.oracle.com/javase/tutorial/essential/regex/

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) somthing as .*/([^!]*)!.*应该这样做...然后你可以使用匹配器找到第一组(括号之间的部分,第0组是整个匹配)

I didn't test this solution... 我没有测试这个解决方案......

You can create a Pattern Object with a regular expression and then create a matcher object from it to parse your String. 您可以使用正则表达式创建一个Pattern对象,然后从中创建一个matcher对象来解析您的String。

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

Pattern p = Pattern.compile (regex);

Matcher m = p.matcher(StringToBeMatched);

if (m.find()) {

    String filename = m.group (1);
}

The simplest way of using them in Java is by using the String.matches method: 在Java中使用它们的最简单方法是使用String.matches方法:

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

That would yield true . 那会产生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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM