简体   繁体   中英

Need regex to match the given string

I need a regex to match a particular string, say 1.4.5 in the below string . My string will be like

absdfsdfsdfc1.4.5kdecsdfsdff 

I have a regex which is giving [c1.4.5k] as an output. But I want to match only 1.4.5 . I have tried this pattern:

[^\\W](\\d\\.\\d\\.\\d)[^\\d] 

But no luck. I am using Java. Please let me know the pattern.

When I read your expression [^\\\\W](\\\\d\\\\.\\\\d\\\\.\\\\d)[^\\\\d] correctly, then you want a word character before and not a digit ahead. Is that correct?

For that you can use lookbehind and lookahead assertions . Those assertions do only check their condition, but they do not match, therefore that stuff is not included in the result.

(?<=\\w)(\\d\\.\\d\\.\\d)(?!\\d)

Because of that, you can remove the capturing group. You are also repeating yourself in the pattern, you can simplify that, too:

(?<=\\w)\\d(?:\\.\\d){2}(?!\\d)

Would be my pattern for that. (The ?: is a non capturing group)

我认为这应该做到: ([0-9]+\\\\.?)+

Regular Expression

((?<!\d)\d(?:\.\d(?!\d))+)

As a Java string:

"((?<!\\d)\\d(?:\\.\\d(?!\\d))+)"

Your requirements are vague. Do you need to match a series of exactly 3 numbers with exactly two dots?

[0-9]+\.[0-9]+\.[0-9]+

Which could be written as

([0-9]+\.){2}[0-9]+

Do you need to match x many cases of a number, seperated by x-1 dots in between?

([0-9]+\.)+[0-9]+

Use look ahead and look behind.

(?<=c)[\d\.]+(?=k)

Where c is the character that would be immediately before the 1.4.5 and k is the character immediately after 1.4.5. You can replace c and k with any regular expression that would suit your purposes

String str= "absdfsdfsdfc**1.4.5**kdec456456.567sdfsdff22.33.55ffkidhfuh122.33.44"; 
String regex ="[0-9]{1}\\.[0-9]{1}\\.[0-9]{1}";  
Matcher matcher = Pattern.compile( regex ).matcher( str);                    
if (matcher.find())
{
String year = matcher.group(0);

System.out.println(year);
}
else
{
    System.out.println("no match found");
}

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