Regular expression to prevent a specific character from appearing before a digit
I want to have a regex in Java to match a pattern where it $
doesn't get to the first occurrence of any digit in a given string. So far I have it ([^$].*?)(\\d+?)
, but it matches lines where $
multiple characters come before the first digit. Am I missing something? For example,
dfn$jnjkdd84fjbd$bjk
must be invalid ( $
preceded by 8
) and
vsdivnsoi5$ier5girneg
valid ( 5
and then $
).
EDIT : The minimum digit must be present in the string.
source to share
^[^$\\d]*[\\d].*$
must do the trick.
We check that all characters before the first digit are not "$" and not a number.
final String invalid = "dfn$jnjkdd84fjbd$bjk";
final String valid = "vsdivnsoi5$ier5girneg";
final String regexp = "^[^$\\d]*[\\d].*$";
System.out.println(invalid.matches(regexp)); // false
System.out.println(valid.matches(regexp)); // true
source to share
You can use a combination of substring()
and matches()
like this:
public static void main(String[] args) {
String s = "adsaa12s$21";
s = s.substring(0, s.indexOf("$")); // upto $
System.out.println(s);
System.out.println(s.matches(".*?\\d.*?")); // does my string contain digits?
}
O / P:
adsaa12s
true
s = "sfs$21";
O/P:
sfs
false
source to share