如何在Java中创建类似SQL的正则表达式

huangapple go评论52阅读模式
英文:

How to create regular expression for java like sql

问题

I want to search using pattern.

String s = "abstract-package-value";

Suppose I want to search for a word that has 'value' in the 3rd position.

I want a pattern like *-*-value

various-paint-kindness

Here, suppose *-paint-*.

In SQL, I can create something like %-paint-%.

英文:

I want to search using pattern.

String s ="abstract-package-value";

Suppose I want to search for word which has 'value' in 3rd position.

I want a pattern like *-*-value

various-paint-kindness

Here, suppose *-paint-*.

In sql, I can make like %-paint-%

答案1

得分: 0

在这个特定的示例中,您可以简单地在输入字符串上使用“-”分割,然后检查第三个元素:

String s = "abstract-package-value";
String[] parts = s.split("-");
if ("value".equals(parts[2])) {
    System.out.println("MATCH");
}

如果您想要一个模式匹配的解决方案,那么使用正则表达式的 String#matches 也是另一个选项:

String s = "abstract-package-value";
if (s.matches(".*-value")) {
    System.out.println("MATCH");
}

您也可以在这里使用 String#endsWith,这与上面给出的 matches 选项类似。

英文:

In this particular example, you may simply split the input string on - and then check the third element:

String s = "abstract-package-value";
String[] parts = s.split("-");
if ("value".equals(parts[2])) {
    System.out.println("MATCH");
}

If you want a pattern matching solution, then String#matches with regex is another option:

String s = "abstract-package-value";
if (s.matches(".*-value")) {
    System.out.println("MATCH");
}

You could also use String#endsWith here as well, which would be similar to the matches option given above.

答案2

得分: 0

尝试这段代码,并使用您想要的变化:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String args[]) {

        String ss = "abstract-package-value";
        Pattern pattern = Pattern.compile(".*-value");
        Matcher mm = pattern.matcher(ss);
        while (mm.find())
            System.out.println("Pattern found from position " + mm.start() + " to " + (mm.end() - 1));
    }
}

输出:

Pattern found from position 0 to 21
英文:

Try this code and use the variations you would like :

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Main {
    
	public static void main(String args[]) { 
        
        String ss ="abstract-package-value";
        Pattern pattern = Pattern.compile(".*-value"); 
        Matcher mm = pattern.matcher(ss); 
        while (mm.find()) 
            System.out.println("Pattern found from position " + mm.start() +   " to " + (mm.end()-1)); 
    } 
}

Output :

Pattern found from position 0 to 21

huangapple
  • 本文由 发表于 2020年7月28日 00:30:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63119521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定