简体   繁体   English

正则表达式匹配字符或数字

[英]Regular Expression match character OR number

I would like to get parts of a string separated by the type (number or character) 我想得到一个由类型(数字或字符)分隔的字符串部分

Simplified initial situation: 简化初始情况:

var content = 'foo123bar456';

Desired result: 期望的结果:

result = ['foo', 123, 'bar', 456];

This is what I have so far to match the first "foo" 这是我到目前为止匹配第一个“foo”

^(([a-z])|([0-9]))+

I thought this would match either characters [az]+ OR numbers [0-9]+ (which would match 'foo' in this case) but unfortunately it allows both (characters AND numbers) at the same time. 我认为这将匹配字符[az] + OR数字[0-9] +(在这种情况下匹配'foo'),但不幸的是它同时允许两个(字符和数字)。

If it would match only characters with the same type I could just add "{1,}" to my regex in order to match all occurrences of the pattern and the world would be a bit better. 如果它只匹配具有相同类型的字符,我可以在我的正则表达式中添加“{1,}”以匹配模式的所有出现,并且世界会更好一些。

Correct regex will be: 正确的正则表达式将是:

([a-zA-Z]+|[0-9]+)

Explanation of the regex is: 正则表达式的解释是:

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [a-zA-Z]+                any character of: 'a' to 'z', 'A' to 'Z'
                             (1 or more times (matching the most
                             amount possible))
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    [0-9]+                   any character of: '0' to '9' (1 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1

使用g修饰符以及全局匹配

[a-zA-Z]+|[0-9]+/g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM