Regex 正则表达式将所有字符匹配到数字(如果有)
我试图找出如何编写一个正则表达式,它将匹配到的每个宪章,但不包括字符序列中的第一个数字(如果有) 例: 输入:abc123 输出:abcRegex 正则表达式将所有字符匹配到数字(如果有),regex,Regex,我试图找出如何编写一个正则表达式,它将匹配到的每个宪章,但不包括字符序列中的第一个数字(如果有) 例: 输入:abc123 输出:abc 输入:#$%@使用字符类功能:[……] 识别号码:[0-9] 否定类:[^0-9] 允许任意数量:[^0-9]*[Update]尝试以下正则表达式: ([^0-9\n]+)[0-9]?.* Regex解释说: ( capturing group starts [^0-9\n] match a single character oth
输入:#$%@使用字符类功能:[……] 识别号码:[0-9] 否定类:[^0-9]
允许任意数量:[^0-9]*[Update]尝试以下正则表达式:
([^0-9\n]+)[0-9]?.*
Regex解释说:
( 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
感谢@Robbie Averill澄清OP的要求 您可以使用:
/^([^\d\n]+)\d*.*$/gm
这也将处理一个字符串中有多组数字的情况
说明:
^ # 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
贪婪匹配意味着默认情况下,您将匹配捕获组,并在捕获组中出现数字或任何不匹配的内容或遇到的字符串结尾时立即停止捕获。我没有选择正确的答案,因为注释中保留了正确的答案。“^\D+” 我在java中工作,所以把所有这些放在一起,我得到了:
Pattern p = Pattern.compile("^\\D+");
Matcher m = p.matcher("Testing123Testing");
String extracted = m.group(1);
您尝试过什么?
^\D+
..问题可能是需要改进;目标似乎是使用正则表达式提取任何数字之前的所有字符,如果没有数字,则提取所有字符。adda123b456
返回a
和b
-OP只希望匹配第一个数字之前的字符digit@RobbieAverill:刚刚更新。谢谢你。