I am working on a project where i need to search for a particular string token and find if this token has the [3:0] format of number, how can i check it? i searched for reference on stack overflow, i could find how to search "{my string }:" in a string like the following:
String myStr = "this is {my string: } ok";
if (myStr.trim().contains("{my string: }")) {
//Do something.
}
But, could not find how to search if a string contains a number in the regular expression, i tried using the following, but it did not work:
String myStr = "this is [3 string: ] ok";
if (myStr.trim().contains("[\\d string: ]")) {
//Do something.
}
Please help!
for "[int:int]" use \\[\\d*:\\d*\\] it's working
You cannot use a regex inside String#contains
, instead, use .matches()
with a regex.
To match [3 string: ]
-like patterns inside larger strings (where string
is a literal word string
), use a regex like (?s).*\\\\[\\\\d+\\\\s+string:\\\\s*\\\\].*
:
String myStr = "this is [3 string: ] ok";
if (myStr.matches("(?s).*\\[\\d+\\s+string:\\s*\\].*")) {
System.out.println("FOUND");
}
See IDEONE demo
The regex will match any number of any characters from the start of string with .*
(as many as possible) before a [
+1 or more digits+1 or more whitespace+ string:
+0 or more whitespace+ ]
+0 or more any characters up to the end of string.
The (?s)
internal modifier makes the dot match newline characters, too.
Note we need .*
on both sides because .matches()
requires a full string match.
To match [3:3]
-like pattern inside larger strings use:
"(?s).*\\[\\d+\\s*:\\s*\\d+\\].*"
Remove \\\\s*
if whitespace around :
is not allowed.
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.