Find the Index of the First Digit in a String

Find the index of the first digit in a string

Use re.search():

>>> import re
>>> s1 = "thishasadigit4here"
>>> m = re.search(r"\d", s1)
>>> if m:
... print("Digit found at position", m.start())
... else:
... print("No digit in that string")
...
Digit found at position 13

How to get index of the first digit in String

firstDigit = 'Testi2ng4'.match(/\d/) // will give you the first digit in the string
indexed = 'Test2ing4'.indexOf(firstDigit)

Well I guess I need to look at my methods more closely, you can just do 'Testin323g'.search(/\d/);

Return the index/position of the first digit/letter in a string in Pandas Dataframe

You can use re.search

import re
df['col1'].apply(lambda x: re.search('\d+', x).start()) + 1

You get

0    4
1 1
2 9

Edit: If there are no matches, re.search().start() will throw attribute error. That needs to be handled in condition. Since Pandas interpret NaN as float, the resulting position will be of float type

df = pd.DataFrame({'col1':['abc12', '33zxy', 'hi_world2','abc']})

df['col1'].apply(lambda x: re.search('\d+', x).start() if re.search('\d+', x) else re.search('\d+', x)) + 1

0 4.0
1 1.0
2 9.0
3 NaN

Find the index of first integer inside a string in order to cut this string

If you are willing to use regular expressions, you can use pattern ^[\d\s]+(.*?)\s+\d.

This will skip all numbers and spaces in beginning of String, and take everything up to a number of spaces followed by a digit.

This will only work if the playerName does not contain a digit (preceded by a space).

String currentPlayerInfo = "97  Dame Zeraphine [TBC]    10  41.458  481 363 117";

Pattern pattern = Pattern.compile("^[\\d\\s]+(.*?)\\s+\\d");

Matcher matcher = pattern.matcher(currentPlayerInfo);
String currentPlayerName;
if (matcher.find()) {
currentPlayerName = matcher.group(1);
} else {
currentPlayerName = null;
}

Locate position of first number in string [R]

Here is a way to return your desired output:

library(stringr)
min(which(!is.na(suppressWarnings(as.numeric(str_split(string, " ", simplify = TRUE))))))

This is how it works:

str_split(string, " ", simplify = TRUE) # converts your string to a vector/matrix, splitting at space

as.numeric(...) # tries to convert each element to a number, returning NA when it fails

suppressWarnings(...) # suppresses the warnings generated by as.numeric

!is.na(...) # returns true for the values that are not NA (i.e. the numbers)

which(...) # returns the position for each TRUE values

min(...) # returns the first position

The output:

min(which(!is.na(suppressWarnings(as.numeric(str_split(string1, " ", simplify = TRUE))))))
[1] 9
min(which(!is.na(suppressWarnings(as.numeric(str_split(string2, " ", simplify = TRUE))))))
[1] 1
min(which(!is.na(suppressWarnings(as.numeric(str_split(string3, " ", simplify = TRUE))))))
[1] 5

Find first sequence of numbers in a string?

If its separated by space, use substring based on the location of first space:

Integer mobId = new Integer(fullMobName.substring(0, fullMobName.indexOf(" "))); 

R: how to find the first digit in a string

Base R

regmatches(string, regexpr("\\d", string))
## [1] "3"

Or using stringi

library(stringi)
stri_extract_first(string, regex = "\\d")
## [1] "3"

Or using stringr

library(stringr)
str_extract(string, "\\d")
## [1] "3"

Given a string find the first embedded occurrence of an integer

There are two issues with this solution.

  1. Consider the test cases - there are 2 characters '8' and '7', and they both form the integer 87 that you should be returning. (This is the main issue)

  2. This is somewhat pedantic, but the integer value of the character '0' isn't necessarily less than the value of '1', '2', etc. It probably almost always is, but I imagine interviewers like to see this sort of care. A better solution would be

    if (Character.isDigit(c)) { ... }

There are plenty of different ways to do this. My first thought would be:

int i = 0;
while (i < string.length() && !Character.isDigit(string.charAt(i))) i++;
int j = i;
while (j < string.length() && Character.isDigit(string.charAt(j))) j++;
return Integer.parseInt(string.substring(i, j)); // might be an off-by-1 here

Of course, as mentioned in the comments, using the regex functionality in Java is likely the best way to do this. But of course many interviewers ask you to do things like this without libraries, etc...



Related Topics



Leave a reply



Submit