0

Basically what I want to do is this:

String mystr = "hello Benjamin Benny Benn hey hey";
String pattern = "Be";

Desired list = {"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.

1
  • 1
    I know how to do this in a really simple way. So please post your code to make your question more clear. Commented Mar 9, 2014 at 10:17

3 Answers 3

2

Use this regex:

Be\w+

What it does?

It matches all the words that start with 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.

Note: You'll need to escape the backslash in java. So \ becomes \\

Sign up to request clarification or add additional context in comments.

4 Comments

Explanation will be very helpful for OP.
@MarounMaroun Done. I've explained
Thanks for the answer, but how can I use this so it gives me a list of all words. like an array of strings. Is there a specific method or something?
You can use myString.matches(regexPattern) to test that. You will have to create the list by looping through each string in the input and testing if the pattern matches. If you are using the Commons Collections, you can use CollectionUtils.filter(list, predicate). See commons.apache.org/proper/commons-collections/javadocs/…, org.apache.commons.collections.Predicate)
1

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 -
word characters (a-z, A-Z, 0-9, _) (1 or more times (matching the most amount possible))

\\s indicates -
whitespace (\n, \r, \t, \f, and " ")

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.