簡體   English   中英

使用JAVA REGEX搜索任何給定的字符串

[英]Search for any given string using JAVA REGEX

我正在嘗試編寫一種通用方法,該方法將在文件中搜索給定的字符串並將其替換為另一個字符串。 我正在使用Java正則表達式相同

patternMatcher = Pattern.compile(searchString);
while ((line = readLine()) != null) {
    Matcher regexMatcher = patternMatcher.matcher(line);
       if (regexMatcher.lookingAt()) {
          line = regexMatcher.replaceAll(replaceString); 

..如此

只要搜索字符串位於文件中每一行的開頭,此邏輯就起作用。 否則將不會發生模式匹配。 有人可以提出解決方案嗎?

例如 我的搜索字符串是“ This”,替換字符串是“ That”
輸入文件包含: This is not This funny
輸出: That is not That funny

但當
輸入文件包含: 007 This is not This funny
輸出: 007 This is not This funny

不應該是...嗎?

patternMatcher = Pattern.compile(searchString);
while ((line = readLine()) != null) {
    Matcher regexMatcher = patternMatcher.matcher(line);
       while (regexMatcher.find()) {
          line = regexMatcher.replaceAll(replaceString); 

考慮到量化詞可能會影響結果,可能搜索字符串應該是“(this)+”或“(this)+?”。

如果要搜索常量字符串而不是模式,則有很多原因不應該使用正則表達式:

  • 用戶可能會鍵入某些在正則表達式語法中具有特殊含義的字符。
  • 與子字符串搜索相比,正則表達式的速度較慢。
  • 您不想允許用戶使用所需的更多功能(使用正則表達式匹配)。

請改用String.indexOf和/或String.replace

while ((line = readLine()) != null)
    if (line.indexOf(searchString) != -1 )
        line.replace(searchString, replaceString);

我對Java不熟悉,但是根據文檔, lookingAt看起來在字符串的開頭。 我只是跳過尋找匹配項而盲目運行replaceAll而不管是否存在匹配項; 如果沒有匹配項,它將什么也不會取代。

如果出於某種原因需要在嘗試替換之前查找匹配項(這很浪費),則find正確的函數。 參見http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Matcher.html

如果內存不是問題,則可以將整個文件讀取為String,並在String API中使用public String replaceAll(String regex, String replacement)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM