正则表达式捕获目录和网站的开始

时间:2016-05-31 19:48:35

标签: java regex replaceall

我正在尝试使用正则表达式来捕获字符串中C:\H:/等的实例,但我遇到了问题。我尝试过(在我的Java代码中)

的几种变体
line = line.replaceAll("[A-Z]:[/\\\\]", " ");

然而它似乎不起作用。我还需要匹配https://,因此可以将其概括为匹配一组不加选择的长度和大写字母,后跟冒号,然后是\/\\//

2 个答案:

答案 0 :(得分:2)

String resultString = subjectString.replaceAll("(?i)[a-z]:(\\\\|/)|https?://", " ");

将使用(空格)替换下面的字符串,不区分大小写:

c:\
d:/
http://
https://

正则表达式解释

[a-z]:(\\\\|/)|https?://

Options: Case insensitive; 

Match this alternative (attempting the next alternative only if this one fails) «[a-z]:(\\\\|/)»
   Match a single character in the range between “a” and “z” (case insensitive) «[a-z]»
   Match the character “:” literally «:»
   Match the regex below and capture its match into backreference number 1 «(\\\\|/)»
      Match this alternative (attempting the next alternative only if this one fails) «\\\\»
         Match the backslash character «\\»
         Match the backslash character «\\»
      Or match this alternative (the entire group fails if this one fails to match) «/»
         Match the character “/” literally «/»
Or match this alternative (the entire match attempt fails if this one fails to match) «https?://»
   Match the character string “http” literally (case insensitive) «http»
   Match the character “s” literally (case insensitive) «s?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match the character string “://” literally «://»


Insert the character “ ” literally « »

答案 1 :(得分:1)

此正则表达式适用于所有四种情况:[A-Z]:[/\\]|https?://

它会捕获一个大写字母,然后是:,然后是\/。或者抓取字母http,跟随或不跟s,后跟://

工作示例:https://regex101.com/r/oH1aW7/1