首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >子字符串的正则表达式,它的前面不应该有数字。

子字符串的正则表达式,它的前面不应该有数字。
EN

Stack Overflow用户
提问于 2014-12-29 07:04:23
回答 2查看 42关注 0票数 2

我使用"[a-z][a-z0-9]*"查找子字符串:

" as4s“-找到as4s "s+sd4“- found s,sd4 “(4 asd悲伤)”-找到了asd,悲伤 "10asd“-发现asd

我需要改变这种体验,这样结果就会是:

" as4s“-找到as4s "s+sd4“- found s,sd4 “(4 4asd)”-发现悲伤 "10asd“-一无所获

可以使用此代码测试表达式:

代码语言:javascript
复制
using System.Text.RegularExpressions;

string input = "A*10+5.01E+10";
Regex r = new Regex("[a-zA-Z][a-zA-Z\d]*");
var identifiers = new Dictionary<string, string>();

MatchEvaluator me = delegate(Match m)
{
    Console.WriteLine(m);
    var variableName = m.ToString();

    if (identifiers.ContainsKey(variableName))
    {
        return identifiers[variableName];
    }
    else
    {
        i++;
        var newVariableName = "i" + i.ToString();
        identifiers[variableName] = newVariableName;
        return newVariableName;
    }
};

input = r.Replace(input, me);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-29 07:05:44

您只需使用单词边界来避免匹配不需要的文本,例如前面有一个数字等等:

代码语言:javascript
复制
Regex r = new Regex("\b[a-zA-Z][a-zA-Z\d]*\b");

RegEx演示

票数 2
EN

Stack Overflow用户

发布于 2014-12-29 07:10:48

代码语言:javascript
复制
(?<!\d)(\b[a-z][a-z0-9]*)

尝试this.Grab capture.See演示。

https://regex101.com/r/gX5qF3/7

代码语言:javascript
复制
NODE                     EXPLANATION
--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    \d                       digits (0-9)
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    \b                       the boundary between a word char (\w)
                         and something that is not a word char
--------------------------------------------------------------------------------
    [a-z]                    any character of: 'a' to 'z'
--------------------------------------------------------------------------------
    [a-z0-9]*                any character of: 'a' to 'z', '0' to '9'
                         (0 or more times (matching the most
                         amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27684742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档