Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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 - Fatal编程技术网

Java 正则表达式以匹配具有一个变量词的句子

Java 正则表达式以匹配具有一个变量词的句子,java,regex,Java,Regex,如何使用正则表达式匹配单词列表 就像我想比赛一样 This is a apple This is a orange This is a peach 我试过这是一个[apple | range | peach] 不起作用 有什么想法吗?关于这一点,我已经发送了5个小时,已经发布了一些“规则”,但没有详尽的示例,这些规则太神秘了。我不确定Java正则表达式,但它将类似于 /(苹果|橙|桃)/ 也就是说,把他们分组,用|来说“或” This is a ((?:(?:apple|orange|peac

如何使用正则表达式匹配单词列表

就像我想比赛一样

This is a apple
This is a orange
This is a peach
我试过
这是一个[apple | range | peach]

不起作用


有什么想法吗?关于这一点,我已经发送了5个小时,已经发布了一些“规则”,但没有详尽的示例,这些规则太神秘了。

我不确定Java正则表达式,但它将类似于

/(苹果|橙|桃)/

也就是说,把他们分组,用|来说“或”

This is a ((?:(?:apple|orange|peach)/?)+)
将匹配

This is a apple/orange/peach.
不管命令是什么

您将只获得一个表示所有列表的捕获组。
(这里是“苹果/橘子/桃子”)

  • (?:apple | orange | peach)
    ”的意思是:匹配这三个术语中的一个,不要捕获它
  • (?:…/?)+
    ”:多次匹配以“/”结尾的字符串
  • (…)
    ”:捕获所有列表

这是一个苹果试试这个:

String str = "This is a peach";
boolean matches = str.matches("(apple|orange|peach)");
如果使用模式,则可以使用

String str = "This is a peach";
Pattern pat = Pattern.compile("(apple|orange|peach)");
Matcher matcher = pat.matcher(str);
boolean matches = matcher.find();
    Pattern pattern = Pattern.compile( "This is a (apple|orange|peach)" );

    Matcher matcher = pattern.matcher( "This is a orange" );
    if( matcher.find() ) {
        System.out.println( matcher.group( 1 ) );
    }
你可以用

String str = "This is a peach";
Pattern pat = Pattern.compile("(apple|orange|peach)");
Matcher matcher = pat.matcher(str);
boolean matches = matcher.find();
    Pattern pattern = Pattern.compile( "This is a (apple|orange|peach)" );

    Matcher matcher = pattern.matcher( "This is a orange" );
    if( matcher.find() ) {
        System.out.println( matcher.group( 1 ) );
    }

不不不不。这是一个我正在使用Java模式的苹果。我怎样才能适应它呢?基本上,如果您使用()而不是[],它会起作用。