【问题标题】:Regex for finding a pattern in a string用于在字符串中查找模式的正则表达式
【发布时间】:2017-05-09 18:17:05
【问题描述】:

我可以有像switchaubcsp-loafsyvgvhv 这样的字符串,它可能包含以下任何模式:s-loafp-loaf 等。

以下是详细要求:

1st character - Any of [p,s,a,r,l], 
2nd character -> [-], Followed by Word [loaf].

在上面的示例中,当搜索[p-loaf] 时,使用java.util.regex 找到了从索引11 开始到索引17 结束的文本p-loaf

正则表达式将是什么来查找第一个字符为Any of [p,s,a,r,l], 2nd character -> [-], Followed by Word [loaf]

【问题讨论】:

  • 您几乎拥有所需的一切,包括接受字符的字符类,以及随后的常量。你试过什么? (而不是期望一切都交给你)
  • @AntonH [psarl][-]loaf

标签: java regex regex-lookarounds regex-greedy regex-group


【解决方案1】:

[psarl]-loaf 如果您希望单词以它开头,请在开头添加^,如果您希望单词以它结尾,请在末尾添加$

你可以在这里试试demo regex

【讨论】:

  • 我认为你有可能因为“请写我的代码”而遭到反对;以防万一你得到一些并想知道为什么。
【解决方案2】:
import java.util.regex.*;
public class RegexExamples {
    public static void main(String[] args) {
        RegexTag("devicexyzas-loafcdbdd", "[psarl][-]loaf");

    }

    public static void RegexTag(Stri`enter code here`ng Content, String PatternToMatch){
        Pattern pattern;
        try {
            pattern = Pattern.compile(PatternToMatch);
        }
        catch (PatternSyntaxException e)
        {
            System.err.println ("Regex syntax error: " + e.getMessage ());
            System.err.println ("Error description: " + e.getDescription ());
            System.err.println ("Error index: " + e.getIndex ());
            System.err.println ("Erroneous pattern: " + e.getPattern ());
            return;
        }

        Matcher matcher = pattern.matcher(Content);

        System.out.println ("Regex = " + Content);
        System.out.println ("Text = " + PatternToMatch);
        System.out.println ();

        while (matcher.find()) {
            System.out.println("Found the text \"" + matcher.group()
                    + "\" starting at " + matcher.start()
                    + " index and ending at index " + matcher.end());
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 2020-10-06
    • 2017-06-07
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多