[英]How to find different occurrences of a substring in a string using regex?
Basically what I want to do is this: 基本上我想做的是这样的:
String mystr = "hello Benjamin Benny Benn hey hey";
String pattern = "Be";
Desired list = {"Benjamin","Benny","Benn"}; 所需列表= {“ Benjamin”,“ Benny”,“ Benn”};
I know how to do this in a really simple way. 我知道如何以一种非常简单的方式做到这一点。 What I am looking for is a fast way to do it based on regex or whatever that works for me.
我正在寻找的是一种基于正则表达式或对我有用的方法的快速方法。 I want a list of all sub-strings(words) starting with a specific pattern.
我想要以特定模式开头的所有子字符串(单词)的列表。
Use this regex: 使用此正则表达式:
Be\w+
It matches all the words that start with Be
它匹配以
Be
开头的所有单词
If you want word starting with anything else, simply do this: 如果您希望单词以其他任何内容开头,只需执行以下操作:
String startsWith="Be"; // change this to match your requirements
String regexPattern=startsWith+"\\w+"; //escaped backslash
Now, you can substitute anything in startsWith
, so you can match words that starts with a specific string. 现在,您可以替换
startsWith
任何内容,以便匹配以特定字符串开头的单词。
Note: You'll need to escape the backslash in java. 注意:您需要在Java中转义反斜杠。 So
\\
becomes \\\\
所以
\\
变成\\\\
Try, 尝试,
String mystr = "hello Benjamin Benny Benn hey hey";
String pattern = "Be";
for(String str : mystr.split("\\s")){
if(str.matches(pattern+"\\w+")){
System.out.println("Matched "+str);
// Add the str to list
}
}
Here, 这里,
\\\\w+
indicates - \\\\w+
表示-
word characters (az, AZ, 0-9, _)
(1 or more times (matching the most amount possible)) 单词字符
(az, AZ, 0-9, _)
(1次或多次(匹配尽可能多的次数))
\\\\s
indicates - \\\\s
表示-
whitespace (\\n, \\r, \\t, \\f, and " ")
空格
(\\n, \\r, \\t, \\f, and " ")
I found this answer which helped me a lot: 我找到了这个答案,这对我有很大帮助:
String yourString = "hi #how are # you";
Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(yourString);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
This way even if your pre-string is separated from the main string it works fine. 这样,即使您的前置字符串与主字符串分开,它也可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.