Regex to prevent trailing spaces and extra spaces

时间:2016-02-12 22:09:31

标签: regex

Right now I have a regex that prevents the user from typing any special characters. The only allowed characters are A through Z, 0 through 9 or spaces.

I want to improve this regex to prevent the following:

  1. No leading/training spaces - If the user types one or more spaces before or after the entry, do not allow.
  2. No double-spaces - If the user types the space key more than once, do not allow.

The Regex I have right now to prevent special characters is as follows and appears to work just fine, which is:

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // ...
    final ListView listview = (ListView) findViewById(R.id.ListView_CallData);
    // ...
}

public void getCallDetails() {
    // ...
    while (managedCursor.moveToNext()) {

    final String phoneNumber = managedCursor.getString(number);
    final String callType = managedCursor.getString(type);
    final String callDate = managedCursor.getString(date);
    final Date callDateTime = new Date(Long.valueOf(callDate));
    final String callDuration = managedCursor.getString(duration);
    // ...
}

Following some other ideas, I tried all these options but they did not work:

^[a-zA-Z0-9 ]+$

Could I get a helping hand with this code? Again, I just want letters A-Z, numbers 0-9, and no leading or trailing spaces.

Thanks.

1 个答案:

答案 0 :(得分:4)

You can use the following regex:

fw=open('file',mode='w',encoding='utf-8')

See regex demo.

The regex will match alphanumerics at the start (1 or more) and then zero or more chunks of a single space followed with one or more alphanumerics.

As an alternative, here is a regex based on lookaheads (but is thus less efficient):

^[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*$

See the regex demo

The ^(?!.* {2})(?=\S)(?=.*\S$)[a-zA-Z0-9 ]+$ disallows consecutive spaces and (?!.* {2}) requires a non-whitespace to be at the end of the string and (?=.*\S$) requires it at the start.