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.

+3


source to share


5 answers


A friend of mine helped me find a really short regex -



^[^$0-9]+[0-9].*

0


source


^[^$\\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

      

+1


source


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

      

0


source


I would use:

^[^\\$]*\\d+[^\\$]*\\$

      

0


source


  (?![^0-9]+\$.*)(?=.*?\d.*?\$.*)(^.*$)

      

use this.This uses lookahead to provide digits up to $.

See demo.

http://regex101.com/r/yX3eB5/8

0


source







All Articles