使用正则表达式计算字符串开头的空格数

时间:2018-08-04 03:00:07

标签: python string whitespace space

如何使用正则表达式计算字符串开头的空格数。例如:

export default class SignupController extends BaseAuthController {

// Variables
// ===============================================================

private confirmPassword: string = '';
private creationDetails: AccountCreationDetails = 
{
    email: '',
    password: ''
}

/**
 * Create an account
 * @returns void
 */
private onCreateAccountClick(): void
{

    if (this.creationDetails && this.creationDetails.email != '')
    {
        if (this.creationDetails && this.creationDetails.password != '')
        {
            if (this.confirmPassword != '')
            {
                if (StringUtil.validateEmail(this.creationDetails.email))
                {
                    if (this.creationDetails.password == this.confirmPassword)
                    {
                        firebase.auth().createUserWithEmailAndPassword(this.creationDetails.email, this.creationDetails.password)
                            .then((respone: firebase.auth.UserCredential) => this.onLoginSuccess(respone))
                            .catch(() => 
                            {
                                this.errorMessage = 'There was an issue creating your account';
                            });
                    }
                    else
                    {
                        this.errorMessage = 'Passwords do not match';
                    }
                }
                else
                {
                    this.errorMessage = 'Please enter a valid email address';
                }
            }
            else
            {
                this.errorMessage = 'Please confirm your password';
            }
        }
        else
        {
            this.errorMessage = 'Please enter a password';
        }
    }
    else
    {
        this.errorMessage = 'Please enter your email address';
        console.log(this.errorMessage);
    }
}
}

count_space变量将为我返回1的值,因为字符串的开头有1个空格。如果我的字符串是:

string = ' area border router'

count_space变量将为我返回2的值,因为字符串的开头有2个空格。依此类推....

我认为表达式将类似于RE ='^ \ s'吗?但不确定如何制定。

1 个答案:

答案 0 :(得分:1)

您不需要正则表达式,只需执行以下操作即可:

s = ' area border router'
print(len(s)-len(s.lstrip()))

输出:

1