英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论