Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式和替换_Java_Regex_Replace_Replaceall - Fatal编程技术网

Java 正则表达式和替换

Java 正则表达式和替换,java,regex,replace,replaceall,Java,Regex,Replace,Replaceall,我是一个Java初学者,上周已经问了一个类似的问题,但是尽管你的回答很有帮助,我仍然没有解决我的问题,所以我想我应该告诉你整个故事。给定一个文本,如 Se不包括任意选择权和[月球旋转权]Gar_1。不包括在任何地方进行仲裁。 不包括第1项规定。 不包括[套利]交易中的交易。 我只想将具有两个标签的字符串(即上述示例中的“[rotura de lunas]”替换为“noGar”)。 我从中获取句子的输入是一个txt文件,我在其中检查正则表达式并最终进行替换 我的代码如下: public clas

我是一个Java初学者,上周已经问了一个类似的问题,但是尽管你的回答很有帮助,我仍然没有解决我的问题,所以我想我应该告诉你整个故事。给定一个文本,如

Se不包括任意选择权和[月球旋转权]Gar_1。不包括在任何地方进行仲裁。
不包括第1项规定。
不包括[套利]交易中的交易。
我只想将具有两个标签的字符串(即上述示例中的“[rotura de lunas]”替换为“noGar”)。 我从中获取句子的输入是一个txt文件,我在其中检查正则表达式并最终进行替换

我的代码如下:

public class Trial_2 {

private static String REGEX = "\\[.*\\](?=(Gar_1|noGar))";  
private static String BE_REPLACED = "Gar_1";  // def part of seq that I want to replace
private static String REPLACE = "noGar";  // def the replacement string     

public static void main(String[] args) throws IOException {

    String input = readFile("corpus_pruebas_multiples_2.txt");
    System.out.println("Original input: " + input);

    Pattern p1 = Pattern.compile(REGEX);  // compare string seq to general pattern 
    Matcher m1 = p1.matcher(input);  // get a matcher object for this general pattern

    if(m1.find( )){
            System.out.println("Found value: " + m1.group(0));  
            Pattern p2 = Pattern.compile(BE_REPLACED);  // compare string to pattern
            Matcher m2 = p2.matcher(input);  // get a matcher object for this pattern
            input = m2.replaceAll(REPLACE);  // replace 
            // print out new string seq with desired replacement:
            System.out.println("Replacement: " + input);  
        } else{
            System.out.println("NO MATCH");
        }     
}


// Method that allows to read from a file by passing it the filename as a param.
      static String readFile(String fileName) throws IOException {

          BufferedReader br = new BufferedReader(new FileReader(fileName));

          try {
              StringBuilder sb = new StringBuilder();
              String line = br.readLine();  

              while(line != null) {
                  sb.append(line);  
                  sb.append("\n");
                  line = br.readLine();  
              }
              return sb.toString(); 
          } finally{
              br.close();
          }
      }
}
我想用
'noGar'
替换字符串标签
'garu 1'
,仅用于具有两个标签的字符串(即上述示例中的
'[rotura de lunas]'

你可以做:

String repl = str.replaceAll("(?<=\\[rotura de lunas\\])Gar_1", "noGar");

String repl=str.replaceAll((?您可以尝试使用由括号捕获的正则表达式的分组功能
()
。此处
$1
表示第一个匹配的组

正则表达式模式:
(\[rotura de lunas\])(Garu 1)

示例代码:

String pattern = "(\\[rotura de lunas\\])(Gar_1)";

String str1 = "Se excluye arbitraje de ley y [rotura de lunas]Gar_1. Se excluye arbitraje de ley y [rotura de lunas]noGar.";
System.out.println(str1.replaceAll(pattern, "$1noGar"));

String str2 = "Excluimos todas aquellas cosas que son afinidad de [Arbitraje de ley]Gar_1.";
System.out.println(str2.replaceAll(pattern, "$1noGar"));
输出:

Se excluye arbitraje de ley y [rotura de lunas]noGar. Se excluye arbitraje de ley y [rotura de lunas]noGar.
Excluimos todas aquellas cosas que son afinidad de [Arbitraje de ley]Gar_1.
下面是演示


如果要添加更多,只需将其添加到regex模式中,该模式由表示或的
分隔

例如

(\[(rotura de lunas)|(blabla)\])(Gar_1)

这将匹配
[rotura de lunas]garu 1
[blabla]garu 1
尝试类似的方法。我基本上做的是检查输入,找到
\[.\\\\](?=(garu 1 | noGar))
,并根据它是否包含
garu 1
noGar
将其粘贴到一个集合中。然后我取两个集合的交点,这样我就有了一个集合,其中包含了发现两者都有出现的字符串。然后我只是用相同的字符串+
noGar>替换了每个字符串+
garu 1

public class Trial_2 {

private static String REGEX = "\\[.*\\](?=(Gar_1|noGar))";  
private static String BE_REPLACED = "Gar_1";  // def part of seq that I want to replace
private static String REPLACE = "noGar";  // def the replacement string     

public static void main(String[] args) throws IOException {

    String input = readFile("corpus_pruebas_multiples_2.txt");
    System.out.println("Original input: " + input);

    Pattern p1 = Pattern.compile(REGEX);  // compare string seq to general pattern 
    Matcher m1 = p1.matcher(input);  // get a matcher object for this general pattern

    Set<String> gar1Set = new HashSet<>();
    Set<String> noGarSet = new HashSet<>();
    while(m1.find( )){
        System.out.println("Found value: " + m1.group());

        String match = m1.group();
        String noLabel = match.substring(0, match.indexOf("]")+1);
        if(match.contains(BE_REPLACED)) {
            gar1Set.add(noLabel);
        }
        else {
            noGarSet.add(noLabel);
        }
    }

    gar1Set.retainAll(noGarSet);
    String replaced = "";
    for(String toReplace : gar1Set) {
        replaced = input.replace(toReplace + BE_REPLACED, toReplace + REPLACE);
    }
    // print out new string seq with desired replacement:
    System.out.println("Replacement: " + replaced);
}


// Method that allows to read from a file by passing it the filename as a param.
      static String readFile(String fileName) throws IOException {

          BufferedReader br = new BufferedReader(new FileReader(fileName));

          try {
              StringBuilder sb = new StringBuilder();
              String line = br.readLine();  

              while(line != null) {
                  sb.append(line);  
                  sb.append("\n");
                  line = br.readLine();  
              }
              return sb.toString(); 
          } finally{
              br.close();
          }
      }
}
public class试用版2{
私有静态字符串REGEX=“\\[.\\](?=(Gar|u 1|noGar))”;
私有静态字符串BE_replacement=“Gar_1”///def我要替换的seq的一部分
私有静态字符串REPLACE=“noGar”//定义替换字符串
公共静态void main(字符串[]args)引发IOException{
String input=readFile(“corpus_pruebas_multiples_2.txt”);
System.out.println(“原始输入:”+输入);
模式p1=Pattern.compile(REGEX);//将字符串seq与常规模式进行比较
matcherm1=p1.Matcher(输入);//获取此常规模式的Matcher对象
Set gar1Set=newhashset();
Set noGarSet=newhashset();
而(m1.find()){
System.out.println(“找到的值:+m1.group());
字符串匹配=m1.group();
字符串noLabel=match.substring(0,match.indexOf(“])+1);
if(匹配包含(被替换)){
gar1Set.add(无标签);
}
否则{
noGarSet.add(noLabel);
}
}
gar1Set.retainal(noGarSet);
字符串“”替换;
用于(字符串替换:gar1Set){
替换=输入。替换(替换+被替换,替换+替换);
}
//打印带有所需替换项的新字符串序列:
系统输出打印项次(“替换:+替换”);
}
//方法,该方法允许通过将文件名作为参数传递来读取文件。
静态字符串读取文件(字符串文件名)引发IOException{
BufferedReader br=新的BufferedReader(新文件读取器(文件名));
试一试{
StringBuilder sb=新的StringBuilder();
String line=br.readLine();
while(行!=null){
某人附加(行);
某人附加(“\n”);
line=br.readLine();
}
使某人返回字符串();
}最后{
br.close();
}
}
}

注意:我还没有测试过这个,所以可能会有一些错误,但我认为它让人明白了我的想法。

我还没有解决我的问题,好吧,但是你的问题是什么?上面已经详细解释过了。我需要一个通用的说法:“如果你有[blablabla]Gar_1[blabla]noGar[bleble]Gar_1[bleble]Gar_1,请替换[blabla]的Gar_1。”noGar没有改变[bleble]的标签1。我如何才能做出选择?你是说,如果你有两个“标签”:
[x]
[y]
,以及标签
[x]
同时出现了
Gar_1
noGar
,那么您想用
noGar
替换
Gar_1
。但是如果标签
[y]
只出现了
Gar_1
,然后不要用
noGar
替换它们?没错!我怎么做?我尝试了各种方法,但都没有完美的效果…我编写的代码替换了所有的“Gar_1”…我认为你不能仅用regex来完成这项工作。我认为你必须扫描你的字符串以查找标签和密码记录下哪一个同时出现Gar_1和noGar。但在这种情况下,它只是“rotura de lunas”,但一般来说它可以是任何字符串,所以我需要一个通用的解决方案。我需要一个通用的方式来表示“如果你有[blabla]Gar_1[blabla]noGar[bleble]Gar_1[bleble]Gar_1,用noGar离开的Gar_1替换[blabla]的Gar_1][bleble]没有改变"。我如何才能做出选择?不,还没有,因为我需要一个更通用的解决方案,它必须适用于任何给定的句子,而不是它们的特定列表…您看到上面基于负面外观的代码了吗?您还可以澄清一下通用解决方案,因为您的问题和注释不够清楚。我的意思是:我有一个很长的txt文件,其中一些gr一组单词用“Gar_1”标记,一些单词组用“noGar”标记,一些单词组用两个标签标记。当我有一组单词同时使用两个标签(即“Gar_1”和“noGar”)时,仅对于这组单词,我想用“noGar”标签替换“Gar_1”标签<
(\[(rotura de lunas)|(blabla)\])(Gar_1)
public class Trial_2 {

private static String REGEX = "\\[.*\\](?=(Gar_1|noGar))";  
private static String BE_REPLACED = "Gar_1";  // def part of seq that I want to replace
private static String REPLACE = "noGar";  // def the replacement string     

public static void main(String[] args) throws IOException {

    String input = readFile("corpus_pruebas_multiples_2.txt");
    System.out.println("Original input: " + input);

    Pattern p1 = Pattern.compile(REGEX);  // compare string seq to general pattern 
    Matcher m1 = p1.matcher(input);  // get a matcher object for this general pattern

    Set<String> gar1Set = new HashSet<>();
    Set<String> noGarSet = new HashSet<>();
    while(m1.find( )){
        System.out.println("Found value: " + m1.group());

        String match = m1.group();
        String noLabel = match.substring(0, match.indexOf("]")+1);
        if(match.contains(BE_REPLACED)) {
            gar1Set.add(noLabel);
        }
        else {
            noGarSet.add(noLabel);
        }
    }

    gar1Set.retainAll(noGarSet);
    String replaced = "";
    for(String toReplace : gar1Set) {
        replaced = input.replace(toReplace + BE_REPLACED, toReplace + REPLACE);
    }
    // print out new string seq with desired replacement:
    System.out.println("Replacement: " + replaced);
}


// Method that allows to read from a file by passing it the filename as a param.
      static String readFile(String fileName) throws IOException {

          BufferedReader br = new BufferedReader(new FileReader(fileName));

          try {
              StringBuilder sb = new StringBuilder();
              String line = br.readLine();  

              while(line != null) {
                  sb.append(line);  
                  sb.append("\n");
                  line = br.readLine();  
              }
              return sb.toString(); 
          } finally{
              br.close();
          }
      }
}