[英]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.