【问题标题】:Java Regex Matching StringsJava 正则表达式匹配字符串
【发布时间】:2012-05-18 16:48:55
【问题描述】:

基本上,我试图在 Java 中匹配字符串中的字符串。例如,我想匹配“hello!there!hello!”中的“hello”,匹配所有的 hello。

我目前有这个,但它不工作:

if(word.matches(wordToMatch)) {
word = word.replaceAll(wordToMatch, plugin.greenyPhrases.get(wordToMatch));
}

任何帮助将不胜感激!

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java regex


【解决方案1】:

你试过了吗

String word = "hello!there!hello!";
word = word.replaceAll("hello", "replaced");

编辑:这是完整的 String 类符号:http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

【讨论】:

  • 它也接受真正的正则表达式。 :) 记得付门人接受哈哈哈
【解决方案2】:

你可以使用 Matcher.find() 来做到这一点

【讨论】:

    【解决方案3】:

    如果要通过matches方法使用regex引擎,需要使用.*

    String word = "hello!there!hello!";
    String requestedWord = "hello"
    
    if( word.matches( ".*" + requestedWord + ".*" ) )
    {
        System.out.println( " This will be printed " );
    }
    

    最好的

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 2013-12-25
      相关资源
      最近更新 更多