-2

I'm trying to figure out how to write a regex that will match every charter up to, but not including the first number in the character sequence if there is one.

Ex:

Input: abc123

Output: abc

Input: #$%@#<>@<123

Output: #$%@#<>@<

Input: abc

Output: abc

Input: abc @#@#@-122

Output: abc @#@#@-

mad_fox
  • 2,578
  • 4
  • 24
  • 36

4 Answers4

0

[Update] Try this regex:

([^0-9\n]+)[0-9]?.*

Regex explains:

(           capturing group starts
[^0-9\n]    match a single character other than numbers and new line
+           match one or more times
)           capturing group ends
[0-9]       match a single digit number (0-9)
?           match zero or more times
.*          if any, match all other than new line

Thanks @Robbie Averill for clarifying OP's requirement. Here is the demo.

Quinn
  • 3,926
  • 2
  • 17
  • 17
0

You can use:

/^([^\d\n]+)\d*.*$/gm

This will also handle scenarios where you have multiple sets of numbers in a string. Example here.

Explanation:

^          # define the start of the stirng
(          # open capture group
  [^\d\n]+ # match anything that isn't a digit or a newline that occurs once or more
)          # close capture group
\d*        # zero or more digits
.*         # anything zero or more times
$          # define the end of the string

g # global
m # multi line

The greedy matching will mean that by default you will match the capture group and stop capturing as soon as either a digit or anything that isn't matched in the capture group or the end of the string it encountered.

scrowler
  • 23,403
  • 9
  • 52
  • 87
0

I did not select a correct answer because the correct answer was left in the comments. "^\D+"

I am working in java, so putting it all together I got:

Pattern p = Pattern.compile("^\\D+");
Matcher m = p.matcher("Testing123Testing");
String extracted = m.group(1);
mad_fox
  • 2,578
  • 4
  • 24
  • 36
-1

Use the character class feature: [...]

Identify numbers: [0-9]

Negate the class: [^0-9]

Allow as many as you like: [^0-9]*

aghast
  • 13,113
  • 1
  • 16
  • 44
  • The question may be need improvement; the objective appears to be the use of Regex to extract all characters before any digits, and all characters if there are no digits. – Osmund Francis Feb 25 '16 at 02:43