Regex to find an integer within a string

后端 未结 6 1368
眼角桃花
眼角桃花 2020-12-31 01:10

I\'d like to use regex with Java.

What I want to do is find the first integer in a string.

Example:

String = \"the 14 dogs ate 12 bones\"
         


        
6条回答
  •  清酒与你
    2020-12-31 01:55

    Heres a handy one I made for C# with generics. It will match based on your regular expression and return the types you need:

    public T[] GetMatches(string Input, string MatchPattern) where T : IConvertible
        {
            List MatchedValues = new List();
            Regex MatchInt = new Regex(MatchPattern);
    
            MatchCollection Matches = MatchInt.Matches(Input);
            foreach (Match m in Matches)
                MatchedValues.Add((T)Convert.ChangeType(m.Value, typeof(T)));
    
            return MatchedValues.ToArray();
        }
    

    then if you wanted to grab only the numbers and return them in an string[] array:

    string Test = "22$data44abc";
    string[] Matches = this.GetMatches(Test, "\\d+");
    

    Hopefully this is useful to someone...

提交回复
热议问题