正则表达式:获取每个在其之前或之后没有其他数字的数字 [英] Regex: get every number that doesn't has an other number before or after itself
问题描述
我必须做的事情是提取每个单个"数字,在它之前或之后没有另一个数字.然后我必须用一个数字替换这个数字,该数字以 1 递增.
The thing that I have to do is to extract every 'single' number, that doesn't has another number right before or after itself. Then I have to replace this number with an number, that is incremented with 1.
我现在想要一个从字符串中获取每个数字的正则表达式,在它之前或之后没有另一个数字.
I now want to a Regex that gets every single number from a string, that doesn't has another number right before or after itself.
例如:
From this string, I just want the '1': "Klasse 1a 14/15" the result should look like "Klasse 2a 14/15"
From this string, I just want the '5': "5/66" the result should look like "6/66"
From this string, I want the '1', '2' and '3': "1/2/3" and the result should look like "2/3/4"
From this string, I just want the '4': "4. Klasse" and the result should look like "5. Klasse"
From this string, I don't want to get anything: "Klasse 99" and the result will remain "Klasse 99"
我目前拥有的是这个正则表达式:
What I have at the Moment is this Regex:
[\D*](\d{1})[\D*]
还有这个方法:
internal string GenerateFollowingSubjectGradeTitle(string currentGradeTitle)
{
var followingGradeTitle = string.Format("{0}{1}{0}", "_", currentGradeTitle);
var regex = new Regex(@"[\D*](\d){1}[\D*] /gm");
var matches = regex.Matches(followingGradeTitle);
if (matches.Count > 0)
{
for (var i = 0; i < matches.Count; i++)
{
var exactmatch = matches[i].Groups[1].Value;
var groupmatch = matches[i].Groups[0].Value;
var intmatch = 0;
if (int.TryParse(exactmatch, out intmatch))
{
var groupreplace = groupmatch.Replace(exactmatch, (intmatch + 1).ToString());
followingGradeTitle = followingGradeTitle.Replace(groupmatch, groupreplace);
}
}
}
return followingGradeTitle.Substring(1, followingGradeTitle.Length - 2);
}
..它主要工作但不是每次都有效.在1/2/3"中,我只得到 1 和 3,但我也需要 2.
..and it works mostly but not everytime. In "1/2/3" I just get the 1 and the 3, but I need the 2 as well.
我知道我的尝试不是最好的方法,如果您有更好的解决方案,请告诉我:)
I know my attempt is not the best way, if you have better solutions, let me know :)
有什么建议吗?
推荐答案
您可以尝试以下基于正则表达式的负面环视.
You could try the below negative lookarounds based regex.
(?<!\d)\d(?!\d)
或
如果您正在运行 javascript,这将起作用.从组索引 1 中选择您想要的数字.环视是不会消耗任何字符的断言.
This would work if you're running javascript. Pick the number you want from group index 1. Lookarounds are assertion which won't consume any character.
(?:^|\D)(\d)(?=\D|$)
这篇关于正则表达式:获取每个在其之前或之后没有其他数字的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!