简体   繁体   中英

Find only first word start from a special character java

I want to find the only first word that start with a "#" sign in a string in java. There cannot be spaces between the sign and the word as well.

The string "hi #how are # you" shall give the output as :

how

I have tried this with regex, but still could not find a suitable pattern. Please help me on this.

Thanks.

String str ="hi #how are # you";
if (str.contains("#")) {
        int pos = str.indexOf("#");

        while (str.charAt(pos + 1) == ' ')
            pos++;


        int last = str.indexOf(" ", pos + 1);

        str = str.substring(pos + 1, last);
        System.out.println(str);
    }
else{

}

output: how

Try this

replaceFirst("^.*?(#\\S+).*$", "$1");

Not exactly beautiful, but should work.

This assume the string has such token. If it does not, then you may want to check whether it matches the regex before extracting the token:

matches("^.*?(#\\S+).*$");

Note that this method will match "#sdfhj" in "sdfkhk#sdfhj sdf" .

If you want to exclude such case, you can modify the regex to "^.*?(?<= |^)(#\\\\S+).*$" .

I assume that xx#xx is wrong word. I thats true try this (if not use "#(\\\\w+)" in Pattern and m.group(1) instead m.group(2) )

String str ="ab cd#ef #gh";
Pattern pattern=Pattern.compile("(^|\\s)#(\\w+)");
Matcher m=pattern.matcher(str);
if(m.find())
    System.out.println(m.group(2));
else
    System.out.println("no match found");

for "ab cd#ef #gh" result -> gh

for "#ab cd#ef #gh" result -> ab

You can try this regex expression:

"[^a-zA-Z][\\S]+?[\\s]"

unless you know what specific character you are looking for to start with in that case

"#[\\S]+?[\\s]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM